Skip to content

Instantly share code, notes, and snippets.

@banderson
Created May 30, 2014 22:38
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 banderson/414c029475ce21157579 to your computer and use it in GitHub Desktop.
Save banderson/414c029475ce21157579 to your computer and use it in GitHub Desktop.
Memoizer: takes in any javascript function and adds memoization based on args
var memoize = function memoize(fn) {
var self = this;
return function newFn() {
newFn.__memo || (newFn.__memo = {});
var args = Array.prototype.slice.call(arguments),
hash = JSON.stringify(args);
return (hash in newFn.__memo)
? newFn.__memo[hash]
: newFn.__memo[hash] = fn.apply(self, args);
};
};
function hello(name) {
return "Hello, "+ name + "! ("+ Date.now() +")";
}
var mello = memoize(hello);
setTimeout(function() {
console.log(mello('Ben', 'Anderson', 'Boom', function() { return true; }));
console.log(hello('Ben', 'Anderson', 'Boom'));
}, 500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment