当前位置:网站首页>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
边栏推荐
- 力扣每日一题-第46天-344. 反转字符串
- Informatics Olympiad All-in-One (1257: Knight Moves)
- Common tools and test methods for interface testing (Introduction)
- 实现fashion_minst服装图像分类
- golang源码分析之geoip2-golang
- 美国爱荷华州立大学| Improving Distantly Supervised Relation Extraction by Natural Language Inference(通过自然语言推理改进远程监督关系提取)
- 博客主页rrs代码
- Xcode13.1 run engineering error fatal error: 'IFlyMSC/IFly h' file not found
- 数字孪生助力智慧城市可视化建设
- Informatics orsay a tong (1258: 【 9.2 】 digital pyramid)
猜你喜欢
封装和包、访问修饰权限
信息学奥赛一本通(1259:【例9.3】求最长不下降序列)
Parse common methods in the Collection interface that are overridden by subclasses
The time series database has been developed for 5 years. What problem does it need to solve?
Common tools and test methods for interface testing (Introduction)
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)
SQL Server安装教程
Qt提升自定义控件,找不到头文件
KDD 2022 | 深度图神经网络中的特征过相关:一个新视角
Li Mu hands-on deep learning V2-BERT pre-training and code implementation
随机推荐
引用类型 ,值类型 ,小坑。
C语言中变量在内存中的保存与访问
Triacetin是什么化学材料
接口测试常用工具及测试方法(入门篇)
unittest自动化测试框架总结
什么是乙二醇二乙酸酯(EGDA)?
李沐动手学深度学习V2-bert预训练数据集和代码实现
golang源码分析之geoip2-golang
Wiring diagrams of switches, motors, circuit breakers, thermocouples, and meters
Solve the docker mysql can't write Chinese
【SLAM】DM-VIO(ros版)安装和论文解读
对话亚洲高校首个博士论文奖-裘捷中丨KDD2022
OpenCV开发中的内存管理问题
你是几星测试/开发程序员?技术型选手王大拿......
一次线上事故,我顿悟了异步的精髓
模板的进阶
Geoip2 - golang golang source code analysis
golang 源码分析:juju/ratelimit
基于“无依赖绝对定位”实现的圣杯三栏布局
EasyExcel实现动态列解析和存表