2014-07-08 58 views
2

我一直在玩meinization的概念,并有明显不同的实现。我把这个在一起,它似乎很好地工作:为什么需要应用于记忆功能?

Function.prototype.memoized = function(a) { 
    debugger 
    if (typeof cache === "undefined") cache = []; 
    if (cache[a]) { 
     return cache[a]; 
    } else { 
     cache[a] = this(a); 
     return cache[a]; 
    } 
} 

Function.prototype.memoize=function() { 
    t=this; 
    return function() { 
    // Resig seems to use this: 
    return t.memoized.apply(t,arguments); 
    // why not simple this: 
    //return t.memoized(arguments[0]); 
    } 

} 

myTest = (function fibonacci(n) { 

    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); 
}).memoize(); 

console.log(myTest(2)); 

我的问题是,为什么却在一些实现我看到 return t.memoized.apply(t,arguments);而不是简单的return t.memoized(arguments[0]);proptotype.memoize里面?除了传递多个未被使用的参数之外,我看不到任何优势。我有没有优势apply

编辑:

更新的代码,我相信这需要照顾的重大问题,使缓存为全球的窗口(我在想什么?),而不是memoizing自身递归调用斐波那契数。我的实施还有其他主要问题吗?

Function.prototype.memoized = function(a) { 

    if (typeof this.cache === "undefined") this.cache = []; 
    if (this.cache[a]) { 
     return this.cache[a]; 
    } else { 
     this.cache[a] = this(a); 
     return this.cache[a]; 
    } 
} 

Function.prototype.memoize=function() { 
    t=this; 
    return function() { 
    //return t.memoized.apply(t,arguments); 
    return t.memoized(arguments[0]); 
    } 

} 

myTest = (function fibonacci(n) { 
    //return a * 3; 

    return n < 2 ? n : fibonacci.memoized(n - 1) + fibonacci.memoized(n - 2); 
}).memoize(); 

console.log(myTest(2)); 

顺便说一句,这是学习我的经验和做纯粹是为了好玩,它不是转让或任何类似的单向关系。

+0

使用'窗口[“缓存”] === undefined'取代'typeof' –

+1

使用'apply'使memoize的功能更多通用的。所以任何数量的参数都可以传递给包装函数。例如,如果您想记忆一个可能需要可变数量参数的add函数。我不明白为什么当通用解决方案稍微复杂时,你会使用't.memoized(arguments [0])'。 – SimpleJ

回答

2

一般来说,JavaScript的功能是variadic,这意味着你需要关注它们的实际情况。一些memoize实现通过将JSON.stringify(arguments)用于缓存密钥来实现此目的。


在这种情况下,它没有任何意义,因为memoized方法不会只用一个参数,也是如此。

但是,在你的代码中有比这个小错误更严重的错误。 cache是一个全局变量,它应该绑定到特定的memoized函数。另外,在递归调用中,您的fib实现为not memoized,实际上它是最重要的。


编辑后的版本看起来不错(全球t变量除外)。在个人,我会缩短/简化了代码一点点但是:

Function.prototype.memoize=function() { 
    var t = this; 
    this.cache = []; 
    return function(a) { 
     var cache = t.cache; 
     if (typeof cache[a] == "undefined") 
      cache[a] = t(a); 
     return cache[a]; 
    }; 
} 

var fibonacci = (function (n) { 
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); 
}).memoize(); 

console.log(fibonacci(2));