缓存函数 memorize
// 缓存函数 Function.prototype.memoize = function () { var _this = this; return function () { const args = Array.prototype.slice.call(arguments); _this.cache = _this.cache || {}; return _this.cache[args] ? _this.cache[args] : (_this.cache[args] = _this.apply(this, args)) } } // 耗时函数 function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)) } // 测试消耗时间 function test(func, ...args) { let result = null; let start = new Date().getTime(); result = func.call(null, ...args) return result.then(() => { console.info(...args) let end = new Date().getTime(); console.info((end - start) + "ms") }) } (async function () { let s = sleep.memoize() await test(s, 2500) // 第一次执行2500参数的耗时 2500ms await test(s, 2500) // 第二次执行2500参数的耗时 0ms 被缓存了 await test(s, 1500) // 第一次执行1500参数的耗时 1500ms await test(s, 2500) // 第三次执行2500参数的耗时 0ms 被缓存了 await test(s, 1500) // 第二次执行1500参数的耗时 0ms 被缓存了 console.info('sleep', sleep.cache); // 打印缓存的参数对应值 })()
参考:https://www.jianshu.com/p/9af1c9c3a02b