2014-07-08 56 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));