Skip to content

Instantly share code, notes, and snippets.

@ariunbat
Created February 1, 2013 18:07
Show Gist options
  • Save ariunbat/4692993 to your computer and use it in GitHub Desktop.
Save ariunbat/4692993 to your computer and use it in GitHub Desktop.
This function helps you save already calculated function's value to the array and prevents you from loading the function again and again. Credit to Douglas Crockford.
/*
Memoizer function takes an initial memo array and fundamental function.
It returns a shell function that manages the memo store and that calls the functamental function as needed.
We pass the shell function and the function's parameters to the fundamental function.
For example: Fibonacci series creater.
var fibonacci = memoizer([0,1], function(shell, n){
return shell(n-1) + shell(n-2);
});
*/
var memoizer = function(memo, fundamental){
var shell = function(n){
var result = memo[n];
if(typeof result !== 'number'){
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment