函数记忆

2017-12-08  本文已影响0人  snakeninja110
  function memorize (f, hasher) {
    var memo = function (name) {
      var cache = memo.cache;
        var key = "" + (hasher ? hasher.apply(this.arguments) : name);
        if (!cache[key]) {
          cache[key] = f.apply(this, arguments);
        }
    }
    memo.cache = {};
    return memo;
  }


  function add (a, b) {
    return a + b;
  }

  var memorizedAdd = memorize(add, function () {
    var args = Array.prototype.slice.call(arguments);
    return  JSON.stringify(args)
  })

console.log(memorizedAdd(1, 2)) // 3
console.log(memorizedAdd(1, 2)) // 不经过计算直接得出3
上一篇 下一篇

猜你喜欢

热点阅读