Last active
September 30, 2015 04:58
-
-
Save evanworley/1725495 to your computer and use it in GitHub Desktop.
make_fast implementation
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
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