Skip to content

Instantly share code, notes, and snippets.

@louisremi
Last active May 14, 2016 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisremi/bb03bceaac428c85929d35323f4ea520 to your computer and use it in GitHub Desktop.
Save louisremi/bb03bceaac428c85929d35323f4ea520 to your computer and use it in GitHub Desktop.
stupid memoize
function memoize(fn) {
var cache = {};
// return a memoized version of the function
return function(arg) {
// intercept the argument
if ( !(arg in cache) ) {
// if it's not in cache, execute the original function and
// cache the result, using the argument as the cache key.
cache[arg] = fn.call(this, arg);
}
// now we're sure that the result is cached, so return it
return cache[arg];
};
}
var nbExecutions = 0;
var square = function(n) {
nbExecutions++;
return n * n;
}
var squareMemoized = memoize(square);
squareMemoized(2); // === 4
// nbExecutions === 1
// cache is { '2': 4 }
squareMemoized(3); // === 9
// nbExecutions === 2
// cache is { '2': 4, '3': 9 }
// when the memoized function is executed with an argument that is already in
// the cache, the result is returned without executing the original function
squareMemoized(2); // === 4
// nbExecutions === 2
// cache is { '2': 4, '3': 9 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment