Skip to content

Instantly share code, notes, and snippets.

@madeindra
Created February 24, 2022 03:36
Show Gist options
  • Save madeindra/cb8580e7f5e0d7a7393ef298978a64ac to your computer and use it in GitHub Desktop.
Save madeindra/cb8580e7f5e0d7a7393ef298978a64ac to your computer and use it in GitHub Desktop.
Memoization with Fibonacci
// find fibonacci number at n index
const fibonacci = (n) => {
// fibonacci at 0 index and at 1 index is always 1
if (n <= 1) {
return 1;
}
// 2 index and later value will be the the sum of the 2 numbers before the index;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// memoization for all functions
const memoizer = (fn) => {
// create cahe
const cache = {};
// return function that have access to the cache
return (n) => {
// check if value exist in cache
if (cache[n] != undefined) {
return cache[n];
}
// if it doesn't exist, calculate the result
cache[n] = fn(n);
return cache[n];
}
}
// combine fibonacci with memoizer, else it will not retain the cache
const memoizedFibonacci = memoizer(fibonacci);
// TEST ELAPSED TIME
const testRepetition = 1000; // test repetition to do
const atIndex = 25; // fibonacci index to find
// WITHOUT MEMOIZATION
// each fibonacci call with the same parameter will be calculated
console.time('without memoization');
for (let i = 0; i < testRepetition; i++) {
fibonacci(atIndex);
}
console.timeEnd('without memoization');
// WITH MEMOIZATION
// only the first fibonacci call with the same parameter will be calculated
// second and later call with the same parameter will be taken from cache
console.time('with memoization');
for (let i = 0; i < testRepetition; i++) {
memoizedFibonacci(atIndex);
}
console.timeEnd('with memoization');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment