Skip to content

Instantly share code, notes, and snippets.

@evanworley
Last active September 30, 2015 04:58
Show Gist options
  • Save evanworley/1725495 to your computer and use it in GitHub Desktop.
Save evanworley/1725495 to your computer and use it in GitHub Desktop.
make_fast implementation
function make_fast(fn) {
var memo = {};
return function (val) {
if(memo[val] === undefined) {
memo[val] = fn(val);
}
return memo[val];
};
}
function expensive(val) {
var result = 0;
for (var i = 0; i < 2000000000; ++i) {
result += val;
}
return result;
}
// Wrap function "expensive" to make subsequent calls with the same parameter fast
var cheap = make_fast(expensive);
// This is still slow
cheap(100);
// But, this is fast
cheap(100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment