js手动实现缓存方法
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); toUpperMemoized("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, lName) => `${fName} ${lName}`; const reduceAdd = (numbers, startingValue = 0) => numbers.reduce((total, cur) => total + cur, startingValue); const memoizedMakeFullName = memoize(makeFullName); const memoizedReduceAdd = memoize(reduceAdd); memoizedMakeFullName("Marko", "Polo"); memoizedMakeFullName("Marko", "Polo"); memoizedReduceAdd([1, 2, 3, 4, 5], 5); memoizedReduceAdd([1, 2, 3, 4, 5], 5);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » js手动实现缓存方法
码云笔记 » js手动实现缓存方法