Skip to content

Instantly share code, notes, and snippets.

@frentsel
Last active November 26, 2018 11:59
Show Gist options
  • Save frentsel/a3f3eaad5aac4c7f4f315d0081aec444 to your computer and use it in GitHub Desktop.
Save frentsel/a3f3eaad5aac4c7f4f315d0081aec444 to your computer and use it in GitHub Desktop.
memoization.js
const memoize = function(fn) {
const cache = {};
return function(...args) {
const key = args.join();
if (cache[key]) {
console.log('from cache!');
return cache[key];
}
return cache[key] = fn.apply(this, args);
};
}
const foo = function(...args) {
return args.reduce((res, el) => res + el, 0);
}
const fn = memoize(foo);
console.log(fn(1, 2)); // 3
console.log(fn(1, 2, 3)); // 6
console.log(fn(1, 2)); // 3 (from cache!)
// https://jsfiddle.net/b9dxfj2u/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment