Skip to content

Instantly share code, notes, and snippets.

@pbalduino
Last active August 29, 2015 13:57
Show Gist options
  • Save pbalduino/9518397 to your computer and use it in GitHub Desktop.
Save pbalduino/9518397 to your computer and use it in GitHub Desktop.
Memoization implemented in JavaScript
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