当前位置:网站首页>js: 实现一个cached缓存函数计算结果
js: 实现一个cached缓存函数计算结果
2022-08-02 20:12:00 【彭世瑜】
实现功能:
第一次执行函数计算到的结果会被缓存,再次调用函数时,函数值直接存缓存结果中获取
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
边栏推荐
- postgresql autovaccum自动清理
- 「 每日一练,快乐水题 」1374. 生成每种字符都是奇数个的字符串
- setup语法糖 defineProps defineEmits defineExpose
- 【SLAM】DM-VIO(ros版)安装和论文解读
- 并发与并行
- 「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
- Which thread pool does Async use?
- "Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
- golang 源码分析:uber-go/ratelimit
- 信息学奥赛一本通(1256:献给阿尔吉侬的花束)
猜你喜欢
.NET performance optimization - you should set initial size for collection types
Electron User Guide Beginning Experience
.NET性能优化-你应该为集合类型设置初始大小
交 叉 数 组
LM小型可编程控制器软件(基于CoDeSys)笔记二十五:plc的数据存储区(数字量输入通道部分)
OP analysis and design
ssdp协议搜索GB28181设备
Implement fashion_minst clothing image classification
GNN教程:图神经网络基础知识!
go——垃圾回收机制(GC)
随机推荐
一次线上事故,我顿悟了异步的精髓
Wintun:一款惊艳的 WireGuard 虚拟网卡接口驱动
Xcode13.1 run engineering error fatal error: 'IFlyMSC/IFly h' file not found
Day12 接口和协议
10 种最佳 IDE 软件 ,你更忠爱哪一个?
Informatics Olympiad All-in-One (1260: [Example 9.4] Intercepting Missiles (Noip1999))
C#异步和多线程
信息学奥赛一本通(1259:【例9.3】求最长不下降序列)
KDD 2022 | 深度图神经网络中的特征过相关:一个新视角
六石管理学:入门机会只有一次,先把产品做好
引用类型 ,值类型 ,小坑。
【手撕AHB-APB Bridge】~ AMBA总线 之 APB
网络协议介绍
笑话:如果你在河边等待得足够久,你会看到你的敌人的尸体漂过,是怎么翻译出来的?
go——内存分配机制
The five classification of software testing
WPF development through practical 】 【 automatic production management platform
OpenCV开发中的内存管理问题
Bena's life cycle
基本语法(三)