緩存函數 memorize

// 緩存函數
Function.prototype.memoize = function () {
  var _this = this;
  return function () {
    const args = Array.prototype.slice.call(arguments);
    _this.cache = _this.cache || {};
    return _this.cache[args] ? _this.cache[args] : (_this.cache[args] = _this.apply(this, args))
  }
}

// 耗時函數
function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)) }

// 測試消耗時間
function test(func, ...args) {
  let result = null;
  let start = new Date().getTime();
  result = func.call(null, ...args)
  return result.then(() => {
    console.info(...args)
    let end = new Date().getTime();
    console.info((end - start) + "ms")
  })
}

(async function () {
  let s = sleep.memoize()
  await test(s, 2500)    // 第一次執行2500參數的耗時 2500ms
  await test(s, 2500)    // 第二次執行2500參數的耗時 0ms 被緩存了
  await test(s, 1500)    // 第一次執行1500參數的耗時 1500ms
  await test(s, 2500)    // 第三次執行2500參數的耗時 0ms 被緩存了
  await test(s, 1500)    // 第二次執行1500參數的耗時 0ms 被緩存了
  console.info('sleep', sleep.cache); // 打印緩存的參數對應值
})()

參考:https://www.jianshu.com/p/9af1c9c3a02b

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章