Last active
November 26, 2018 11:59
-
-
Save frentsel/a3f3eaad5aac4c7f4f315d0081aec444 to your computer and use it in GitHub Desktop.
memoization.js
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
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