当前位置:网站首页>浅聊缓存函数
浅聊缓存函数
2022-08-03 09:06:00 【InfoQ】

const calculate = (num)=>{
const startTime = new Date()
for(let i=0;i<num;i++){} // 大数计算
const endTime = new Date()
return endTime - startTime
}
console.log(calculate(10_000_000_000))
// 10465
calculate(10_000_000_000)let result = calculate(10_000_000_000)resultresultlet result = calculate(10_000_000_000)
let result1 = calculate(10_000_000_0000)
......
let resultN = calculate(10_000_000_0000...000)
calculatelet cacheObj = {}
const calculate = (num)=>{
if(!cacheObj[num]){
const startTime = new Date()
for(let i=0;i<num;i++){}
const endTime = new Date()
cacheObj[num] = endTime - startTime
}
return cacheObj[num]
}
calculatebalculatedalculate/*
* 缓存函数 cashed
*/
function cached(fn){ // 传入需要缓存结果的函数
const cacheObj = Object.create(null); // 创建一个对象
return function cachedFn (str) { // 返回回调函数
if ( !cacheObj [str] ) { // 在对象里面查询,函数结果是否被计算过
let result = fn(str);
cacheObj [str] = result; // 没有则要执行原函数,并把计算结果缓存起来
}
return cacheObj [str] // 被缓存过,直接返回
}
}
// calculate 计算大数的函数(也可以叫原函数)
const calculate = (num)=>{
const startTime = new Date()
for(let i=0;i<num;i++){}
const endTime = new Date()
return endTime - startTime
}
// 经过缓存函数 cashed 将原函数 calculate 封装,让原函数具有缓存的新功能
let cashedCalculate = cached(calculate)
cashedCalculate(10_000_000_000) // 10465
cashedCalculatecashedCalculate(10_000_000_000) // 10465
边栏推荐
猜你喜欢
随机推荐
STP生成树选举结果查看及验证
深度学习之 10 卷积神经网络2
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二:编码实现
redis stream 实现消息队列
10 minutes to get you started chrome (Google) browser plug-in development
What are pseudo-classes and pseudo-elements?The difference between pseudo-classes and pseudo-elements
批量将PNG格式转化为JPG格式
验证浮点数输入
gpnmb+ gpnmb-AT2 cell空转映射 上皮细胞的空转映射
Industry SaaS Microservice Stability Guarantee Actual Combat
Add Modulo 10 (规律循环节,代码实现细节)
dflow入门1——HelloWorld!
开发工具之版本控制
MySQL-TCL语言-transaction control language事务控制语言
110道 MySQL面试题及答案 (持续更新)
scala reduce、reduceLeft 、reduceRight 、fold、foldLeft 、foldRight
Machine learning (formula derivation and code implementation)--sklearn machine learning library
unity的game界面里有canvas的线框?如何隐藏掉?
【LeetCode】622. Design Circular Queue
行业洞察 | 如何更好的实现与虚拟人的互动体验?









