JSFiddle - React, Tailwind, and code Playground
by Robodude
JavaScript
function cacher(fn){
const cache = new Map()
return (...args) => {
const params = [...args]
const key = {}
params.forEach((p, i) => {
key[i] = p
})
console.log(key)
console.log(Array.from(cache))
const isCached = cache.has(key)
if (isCached){
console.log("from cache")
const cachedValue = cache.get(key)
return cachedValue
}
else {
const result = fn(...args);
cache.set(key, result)
return result
}
}
}
const sum = (a, b) => a + b
const cachedSum = cacher(sum)
console.log("a: ", cachedSum(2, 3))
console.log("b: ", cachedSum(2, 3))
console.log("c: ", cachedSum(2, 3))