Created
May 30, 2014 22:38
-
-
Save banderson/414c029475ce21157579 to your computer and use it in GitHub Desktop.
Memoizer: takes in any javascript function and adds memoization based on args
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
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