A Pen by Mingkai Cao on CodePen.
Last active
September 1, 2019 17:50
-
-
Save caomingkai/497982bda7dd85d9fcfa9b7012e27637 to your computer and use it in GitHub Desktop.
Cache a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cache(fn) { | |
let cache = new Map(); | |
let cachedFn = function(...args) { | |
const key = args.join('.'); | |
if (cache.has(key)) { | |
return cacha.get(key); | |
} | |
const res = fn.apply(this, args); | |
cache.set(key, res); | |
return res; | |
} | |
cachedFn.cache = cache; | |
return cachedFn; | |
} | |
// test | |
let cost = function(a, b, c) { | |
let res = 0; | |
for (let i = 0; i < 100; i++) { | |
res += a * i + b + c; | |
} | |
return res; | |
} | |
let cached = cache(cost); | |
console.time("2, 2, 2: 1st time"); | |
console.log(cached(2,2,2)); | |
console.timeEnd("2, 2, 2: 1st time"); | |
console.time("2, 2, 2: 2nd time"); | |
console.log(cached(2,2,2)); | |
console.timeEnd("2, 2, 2: 2nd time"); | |
console.time("3,3,3: 1st time"); | |
console.log(cached(2,2,2)); | |
console.timeEnd("3,3,3: 1st time"); | |
console.time("3,3,3: 2nd time"); | |
console.log(cached(2,2,2)); | |
console.timeEnd("3,3,3: 2nd time"); | |
console.log(cached.cache); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cache a function