Skip to content

Instantly share code, notes, and snippets.

@caomingkai
Last active September 1, 2019 17:50
Show Gist options
  • Save caomingkai/497982bda7dd85d9fcfa9b7012e27637 to your computer and use it in GitHub Desktop.
Save caomingkai/497982bda7dd85d9fcfa9b7012e27637 to your computer and use it in GitHub Desktop.
Cache a function
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);
@caomingkai
Copy link
Author

cache a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment