Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Created September 18, 2011 16:33
Show Gist options
  • Save addyosmani/1225243 to your computer and use it in GitHub Desktop.
Save addyosmani/1225243 to your computer and use it in GitHub Desktop.
memoize.js - a faster JavaScript memoizer
/*
* memoize.js
* by @philogb and @addyosmani
* further optimizations by @mathias
* Released under an MIT license.
*/
function memoize( fn ) {
return function () {
var args = Array.prototype.slice.call(arguments),
hash = "",
i = args.length;
toString = Object.prototype.toString,
callEm = toString.call({}),
currentArg=null;
while(i--){
currentArg = args[i];
hash += (callEm == toString.call(currentArg)) ?
JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize || {});
//old: fn.memoize = fn.memoize || {};
}
return (hash in fn.memoize) ? fn.memoize[hash] :
fn.memoize[hash] = fn.apply( this , args );
};
}
@mathiasbynens
Copy link

fn.memoize || (fn.memoize || {}); should be fn.memoize || (fn.memoize = {}); — sorry for the typo on IRC!

@addyosmani
Copy link
Author

Thanks Mathias! :)

@aaaia
Copy link

aaaia commented Nov 27, 2019

I beliwe that cache (memoize) object should be connected with result rather than with source function.
This way creating multiple memoized functions from thesame source function do not result in overlapping cache entries.

Ex.:

function(_thiz, _fn) { var _cache = undefined _cache = {}; var _r = (function(thiz, fn, cache){ 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; } cache.repo || (cache.repo = {}) cache.clearCache = function() { cache.repo = {}; }; return (cache.repo.hasOwnProperty(hash)) ? cache.repo[hash] : cache.repo[hash] = fn.apply(thiz, args); }; })(_thiz, _fn, _cache) _r._cache = _cache; return _r; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment