Created
September 3, 2014 16:52
-
-
Save xaviervia/c2cce9c5a22b4c8f1088 to your computer and use it in GitHub Desktop.
Self memoizing JavaScript function
This file contains 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
// Naming an otherwise anonymous function creates the named reference inside the | |
// function's scope. We use `cache` as the internal name | |
var selfMemoizing = function cache(input) { | |
// Let's prepare a cache object called "memoize" if not available | |
cache.memoized = cache.memoized || {} | |
// Return the cached result if available | |
if (cache.memoized[input]) return cache.memoized[input] | |
// Create the cache at the time of returning the result | |
return cache.memoized[input] = input + " remembered!" | |
} | |
// That's it! Short, sweet, with no dependencies and no closures. You can even | |
// prepare the memoization to work with several arguments using a "multidimensional" | |
// object structure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment