function memoize(fn) {
const cache = {};
return function (param) {
if (cache[param]) {
console. log(‘cached’);
return cache[param];
} else {
let result = fn(param);
cache[param] = result;
console. log( not cached );
return result;
}
}
}
const toUpper = (str ="")=> str. toUpperCase();
const toUpperMemoized = memoize(toUpper);
toUpperMemoi zed("abcdef");
toUpperMemoized("abcdef");
这个缓存函数适用于接受一个参数。我们需要改变下,让它接受多个参数。
const slice = Array. Prototype. slice;
function memoize(fn) {
const cache = {};
return (… args) => {
const params = slice. call(args);
console. log(params);
if (cache[params]) {
console. log(‘cached’);
return cache[params];
} else {
let result = fn(… args);
cache[params] = result;
console. log( not cached );
return result;
}
}
}
const makeFullName = (fName, IName) => {fName} {IName}
const reduceAdd = (numbers, startingValue = 0) => numbers. reduce ((total, cur) => total + cur,
startingValue);
const memoizedMakeFulIName = memoize (makeFullName);
const memoizedRedueeAdd = memoize(reduceAdd);
memoizedMakeFulIName("Marko", "Polo");
memoizedMakeFullName("Marko", "Polo");
memoizedReduceAdd([1, 2, 3, 4, 5], 5);
memoizedReduceAdd([1, 2, 3, 4, 5], 5);

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.