当前位置:网站首页>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
边栏推荐
- 【StoneDB性能相关工具】内存监控
- go——内存分配机制
- .NET performance optimization - you should set initial size for collection types
- 浅议.NET遗留应用改造
- golang源码分析:time/rate
- PG's SQL execution plan
- Parse common methods in the Collection interface that are overridden by subclasses
- 接口测试常用工具及测试方法(入门篇)
- ALV report learning summary
- 奥特学园ROS笔记--7(289-325节)
猜你喜欢

Parse common methods in the Collection interface that are overridden by subclasses

信息学奥赛一本通(1258:【例9.2】数字金字塔)

框架设计:PC 端单页多页框架如何设计与落地

PG's SQL execution plan

Translate My Wonderful | July Moli Translation Program Winners Announced

软件测试的流程规范有哪些?具体要怎么做?

Wiring diagrams of switches, motors, circuit breakers, thermocouples, and meters

一款免费的容器安全 SaaS 平台使用记录

Triacetin是什么化学材料

Digital twins help visualize the construction of smart cities
随机推荐
setup syntax sugar defineProps defineEmits defineExpose
数字孪生助力智慧城市可视化建设
网络协议介绍
用了TCP协议,就一定不会丢包吗?
APP自动化uiautomator2获取toast
并发与并行
引用类型 ,值类型 ,小坑。
[AnXun cup 2019] easy_web
Bena's life cycle
SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
什么是 IDE
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)
js如何获取浏览器缩放比例
Thread线程类基本使用(上)
Meta 与苹果的元宇宙碰撞
golang 源码分析:juju/ratelimit
J9 Digital Currency Theory: Identifying Web3's New Scarcity: Open Source Developers
TodoList案例
接口测试常用工具及测试方法(入门篇)
js Fetch返回数据res.json()报错问题