0
点赞
收藏
分享

微信扫一扫

js: 实现一个cached缓存函数计算结果


实现功能:

第一次执行函数计算到的结果会被缓存,再次调用函数时,函数值直接存缓存结果中获取

function cached(func) {
// 缓存计算结果
const cache = Object.create(null)

// 返回一个缓存函数
return function (...args) {
let cache_key = JSON.stringify(args)

let result = null
if (cache_key in cache) {
result = cache[cache_key]
} else {
result = func.apply(this, args)
cache[cache_key] = result
}

return result
}
}

使用示例

function computed(a,) {
console.log('computed')
return a + b
}

let cachedComputed = cached(computed)

console.log(cachedComputed(2, 3))

console.log(cachedComputed(2, 3))
// 只计算了一次
// computed
// 5
// 5

参考
​​​分享 14 个你必须知道的 JS 函数​​


举报

相关推荐

0 条评论