Skip to content

Instantly share code, notes, and snippets.

@edgarberm
Created March 28, 2016 11:50
Show Gist options
  • Save edgarberm/d7dd03aa2eff12a009dd to your computer and use it in GitHub Desktop.
Save edgarberm/d7dd03aa2eff12a009dd to your computer and use it in GitHub Desktop.
Memoization for JavaScript
/*
* memoize.js
* by @philogb and @addyosmani
* with further optimizations by @mathias
* and @DmitryBaranovsk
* perf tests: http://bit.ly/q3zpG3
* Released under an MIT license.
*/
function memoize( fn ) {
return function () {
var args = Array.prototype.slice.call(arguments),
hash = "",
i = args.length;
currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ?
JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize = {});
}
return (hash in fn.memoize) ? fn.memoize[hash] :
fn.memoize[hash] = fn.apply(this, args);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment