美文网首页
函数记忆

函数记忆

作者: snakeninja110 | 来源:发表于2017-12-08 00:00 被阅读0次
      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
    

    相关文章

      网友评论

          本文标题:函数记忆

          本文链接:https://www.haomeiwen.com/subject/ksojixtx.html