Last active
August 29, 2015 13:57
-
-
Save pbalduino/9518397 to your computer and use it in GitHub Desktop.
Memoization implemented in JavaScript
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 memoize(fun) { | |
var mem = {}; | |
return function() { | |
var args = arguments.toString(); | |
if(mem[args] == undefined) { | |
mem[args] = fun.apply(this, arguments); | |
} | |
return mem[args]; | |
} | |
} | |
// usage: | |
function slow(x) { | |
for(var p = 0; p < 999000000; p++) { } | |
return x; | |
} | |
var memoSlow = memoize(slow); | |
slow(10); // runs very slow | |
memoSlow(10); // runs very slow | |
memoSlow(10); // runs very fast |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment