我被问到这个问题,我不知道我该如何瞄准这个。JavaScript写一个函数缓存一个函数(记忆)
问:
编写一个缓存的功能,并返回如果 它在过去已经执行结果的缓存功能。
Let's say if there's a function Fibonacci(20) = 6765
cacheFunction(Fibonacci(20)) // it should not execute the function instead return 6765.
But if i give cacheFunction(Fibonacci(21)) //It's not cached, execute the function
我尝试:
function cacheFunction(funct) {
var obj = {};
if (obj.hasOwnProperty(funct)) { //checking if the argument is in the object?
return obj[funct];
} else { //if not present, then execute the function, store it in cache and return the value.
obj[funct];
return funct;
}
}
但我无法理解如何让参数在一个函数另一个函数里面? (这个人告诉我,我需要使用关闭来获得它)
有人能够启发我吗?
BTW:http://stackoverflow.com/search?q=javascript+memoize –
可能重复[Javascript Memoization Explanation?](http://stackoverflow.com/questions/8548802/javascript-memoization-explanation) – m0meni