Created
March 28, 2016 11:50
-
-
Save edgarberm/d7dd03aa2eff12a009dd to your computer and use it in GitHub Desktop.
Memoization for JavaScript
This file contains hidden or 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
/* | |
* 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