当前位置:网站首页>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
边栏推荐
猜你喜欢
![[AnXun cup 2019] easy_web](/img/26/c04bc8b9c65ac75ddd2696b48e1661.png)
[AnXun cup 2019] easy_web

ssdp协议搜索GB28181设备

成为黑客不得不学的语言,看完觉得你们还可吗?

Implement fashion_minst clothing image classification

Li Mu hands-on deep learning V2-BERT pre-training and code implementation

Electron User Guide Beginning Experience

9,共模抑制比一-不受输入信号中共模波动的影响。【如何分析共模CM抑制比。】

Day35 LeetCode

Digital twins help visualize the construction of smart cities

Li Mu hands-on learning deep learning V2-bert and code implementation
随机推荐
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
谷歌竞价机器学习如何去理解?
【StoneDB性能相关工具】内存监控
Xcode13.1运行工程报错fatal error: ‘IFlyMSC/IFly.h‘ file not found的问题
SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
即时通讯开发移动端网络短连接的优化手段
ABAP grammar small review
pytorch的tensor创建和操作记录
什么是 IDE
Which thread pool does Async use?
golang源码分析:time/rate
Async的线程池使用的哪个?
The time series database has been developed for 5 years. What problem does it need to solve?
信息学奥赛一本通(1258:【例9.2】数字金字塔)
.NET性能优化-你应该为集合类型设置初始大小
Wiring diagrams of switches, motors, circuit breakers, thermocouples, and meters
【手撕AHB-APB Bridge】~ AMBA总线 之 APB
「 每日一练,快乐水题 」1374. 生成每种字符都是奇数个的字符串
Triacetin是什么化学材料
OpenCV开发中的内存管理问题