Created
March 5, 2014 15:06
-
-
Save peterpme/9369015 to your computer and use it in GitHub Desktop.
Javascript: Memoization with Simple Example using addMe function
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
// Simple Memoization - could use some work | |
function addMe(num){ | |
return num+num; | |
} | |
function memoMe(fn){ | |
var objs = {}; | |
return function(x){ | |
if(x in objs) | |
{ | |
console.log(x + ' was pulled from cache'); | |
} | |
else | |
{ | |
// assign objs[x] to the function being passed in | |
objs[x] = fn(x); | |
console.log(x + ' was added to cache'); | |
} | |
return objs[x]; | |
}; | |
} | |
var test = memoMe(addMe); | |
console.log("Answer: " + test(5)); | |
console.log("Answer: " + test(5)); | |
console.log("Answer: " + test(10)); | |
console.log("Answer: " + test(6)); | |
console.log("Answer: " + test(6)); | |
console.log("Answer: " + test(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment