Last active
April 24, 2016 21:09
-
-
Save jafow/aee10565d464a17f7074 to your computer and use it in GitHub Desktop.
Example memoize implementations
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
/** Memoize takes a function as an argument and returns a function. When the supplied function is called, it is stored in a | |
* lookup table. That way the next time it's called the passed function won't run again and will instead return the stored value. | |
*/ | |
function memoize (fn) { | |
var cache {} | |
return function () { | |
var args = Array.prototype.slice.call(arguments) | |
var key = JSON.stringify(args) | |
if (key in cache) return cache[key] | |
else { | |
return cache[key] = fn.apply(this, args) | |
} | |
} | |
} | |
// ES6 implementation with rest operator | |
const memoize = (fn) => { | |
let cache = {} | |
return function (...args) { | |
let stored = JSON.stringify(args) | |
return cache[stored] || (cache[stored] = fn.apply(this, args)) | |
} | |
// example | |
const fibMem = memoize((n) => n < 2 ? 1 : fibMem(n - 2) + fibMem(n - 1)) | |
fibMem(100) // => 573147844013817200000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment