Lodash memoize method
语法
_.memoize(func, [resolver])
Creates a function that memoizes the result of func. If resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with the this binding of the memoized function.
参数
func (Function) − The function to have its output memoized.
[resolver] (Function) − The function to resolve the cache key.
输出
(Function) − Returns the new memoized function.
实例
var _ = require('lodash');
var fibonacci = _.memoize(function(n) {
return n < 2 ? n: fibonacci(n-1) + fibonacci(n-2);
});
var fibonacci1 = function(n) {
return n < 2 ? n: fibonacci1(n-1) + fibonacci1(n-2);
};
var startTimestamp = new Date().getTime();
var result = fibonacci(1000);
var endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp-startTimestamp)) + ' ms');
startTimestamp = new Date().getTime();
result = fibonacci1(30);
endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp-startTimestamp)) + ' ms');
Save the above program in
tester.js. Run the following command to execute this program.
Command
输出
4.346655768693743e+208 in 3 ms
832040 in 551 ms