Created
January 14, 2019 20:57
-
-
Save celwell/c609f6160263f2fc0b505e2c038c183d to your computer and use it in GitHub Desktop.
JS function "memoize": Takes a function, f, and returns a memoized version of f.
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
// Takes a function, f, and returns a memoized version of f. | |
// Note: only memoize pure, idempotent functions | |
var memoize = function (f) { | |
let store = new Map(); | |
return function (...args) { | |
const k = JSON.stringify(args); | |
return (store.has(k) ? | |
store.get(k) : | |
store.set(k, f(...args)).get(k)); | |
}; | |
}; | |
/* | |
Example usage: | |
var do_sum = function (x, y) { | |
console.log('did calculation'); | |
return x + y; | |
}; | |
var memoized_do_sum = memoize(do_sum); | |
memoized_do_sum(3, 12); | |
// output: "did calculation", 15 | |
memoized_do_sum(3, 12); | |
// output: 15 | |
memoized_do_sum(3, 12); | |
// output: 15 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment