Created
February 1, 2013 18:07
-
-
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.
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
/* | |
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