Skip to content

Instantly share code, notes, and snippets.

@xaviervia
Created September 3, 2014 16:52
Show Gist options
  • Save xaviervia/c2cce9c5a22b4c8f1088 to your computer and use it in GitHub Desktop.
Save xaviervia/c2cce9c5a22b4c8f1088 to your computer and use it in GitHub Desktop.
Self memoizing JavaScript function
// 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