Skip to content

Instantly share code, notes, and snippets.

@peterpme
Last active August 29, 2015 13:57
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 peterpme/9355237 to your computer and use it in GitHub Desktop.
Save peterpme/9355237 to your computer and use it in GitHub Desktop.
Javascript: Memoization - passing in the function instead of setting objs[x] equal to the arguments.
// 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