Last active
May 7, 2019 01:26
-
-
Save dino-su/c4444414cf389507a588ee382db25a82 to your computer and use it in GitHub Desktop.
Fibonacci Memoization
This file contains hidden or 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
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