Skip to content

Instantly share code, notes, and snippets.

@dino-su
Last active May 7, 2019 01:26
Show Gist options
  • Save dino-su/c4444414cf389507a588ee382db25a82 to your computer and use it in GitHub Desktop.
Save dino-su/c4444414cf389507a588ee382db25a82 to your computer and use it in GitHub Desktop.
Fibonacci Memoization
function proxy(fn) {
const cache = {};
return function (arg) {
// add function result to cache
if (cache[arg] === undefined) cache[arg] = fn.call(this, arg);
return cache[arg];
}
}
function fib(n) {
if (n < 2) return n;
return fibProxy(n - 1) + fibProxy(n - 2);
}
// the cache setup
const fibProxy = proxy(fib);
const start = new Date().getTime();
console.log(`Successione di Fibonacci 78: ${fibProxy(78)}, Execution Time: ${new Date().getTime() - start} ms`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment