js: 实现一个cached缓存函数计算结果
        【摘要】 
                    
                        
                    
                    实现功能: 
第一次执行函数计算到的结果会被缓存,再次调用函数时,函数值直接存缓存结果中获取 
function cached(func) {
  // 缓存计算结果
  const cache = Ob...
    
    
    
    实现功能:
第一次执行函数计算到的结果会被缓存,再次调用函数时,函数值直接存缓存结果中获取
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
  }
}
  
 
 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
使用示例
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
  
 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/126117903
        【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
            cloudbbs@huaweicloud.com
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
            
 
           
评论(0)