Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created December 15, 2017 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/aa0a0887f8ac92c98418a7a2d2c2cc95 to your computer and use it in GitHub Desktop.
Save ycmjason/aa0a0887f8ac92c98418a7a2d2c2cc95 to your computer and use it in GitHub Desktop.
// Simple memoization, done
const memoize = (fn) => {
const memo = {};
return function(...args){
const hash = JSON.stringify(args);
if(hash in memo) return memo[hash];
return fn(...args);
};
};
const fib = (n) => (n < 2)? 1: fib(n-2) + fib(n-1);
const smart_fib = memoize((n) =>(n < 2)? 1: smart_fib(n-2) + smart_fib(n-1));
fib(100); // don't try, probably takes forevery
smart_fib(100); // yeah! quick and nice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment