Skip to content

Instantly share code, notes, and snippets.

@Syrup-tan
Last active August 29, 2015 14:15
Show Gist options
  • Save Syrup-tan/6664a9ca52eacffdc59d to your computer and use it in GitHub Desktop.
Save Syrup-tan/6664a9ca52eacffdc59d to your computer and use it in GitHub Desktop.
Memoization function for ECMAScript
// Get the nth fibonacci number, starting from fib(0) == 1
var fib = Memoize(function(n) {
if (n == 0) return 1;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
});
// Define the Memoize function
function Memoize(f) {
// Results of previous calls
var results = {};
// Return the memoized function
return function() {
// Need to use JSON.stringify because;
// Symbol.for([1,2]) === Symbol.for('1,2')
// results[[1,2]] === results['1,2']
var key = JSON.stringify(arguments);
// Return the result if we have it cached
return results[key] || (
// Otherwise calculate it, cache it, then return it
results[key] = f.apply(null, arguments)
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment