您当前的位置: 首页 >  缓存

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2022-08-02 10:51:08 ,浏览量:3

实现功能:

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

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, b) {
  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 函数

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0546s