Skip to content

Instantly share code, notes, and snippets.

@voronianski
Created November 11, 2014 19:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voronianski/f0507ecd0d1c35eaf519 to your computer and use it in GitHub Desktop.
Save voronianski/f0507ecd0d1c35eaf519 to your computer and use it in GitHub Desktop.
Memoization implementations
// Underscore.js
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Lodash.js
function MemCache() {
this.__data__ = {};
}
function memGet(key) {
return this.__data__[key];
}
function memHas(key) {
return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
}
function memSet(key, value) {
if (key != '__proto__') {
this.__data__[key] = value;
}
return this;
}
MemCache.prototype.get = memGet;
MemCache.prototype.has = memHas;
MemCache.prototype.set = memSet;
function memoize(func, resolver) {
if (!isFunction(func) || (resolver && !isFunction(resolver))) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : arguments[0];
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, arguments);
cache.set(key, result);
return result;
};
memoized.cache = new memoize.Cache;
return memoized;
}
memoize.Cache = MemCache;
// Addy Osmani's memoize.js
// http://addyosmani.com/blog/faster-javascript-memoization/
var memoize = function(func) {
var stringifyJson = JSON.stringify,
cache = {};
var cachedfun = function() {
var hash = stringifyJson(arguments);
return (hash in cache) ? cache[hash] : cache[hash] = func.apply(this, arguments);
};
cachedfun.__cache = (function() {
cache.remove || (cache.remove = function() {
var hash = stringifyJson(arguments);
return (delete cache[hash]);
});
return cache;
}).call(this);
return cachedfun;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment