Created
August 6, 2020 21:57
-
-
Save Hoxtygen/bd17bb3675a0100669dd380ba8924e52 to your computer and use it in GitHub Desktop.
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
//Basic fibonacci function | |
function fib(value) { | |
if (value <= 1) { | |
return value; | |
} | |
return fib(value - 1) + fib(value - 2); | |
} | |
// memoization with IIFE | |
const memoizedFib = (() => { | |
const cache = {}; | |
let value; | |
function fibonacci(x) { | |
if (cache[x]) { | |
value = cache[x]; | |
} else { | |
if (x <=) { | |
value = x; | |
} else value = fib(x - 1) + fib(x - 2); | |
cache[x] = value; | |
} | |
return value; | |
} | |
return fibonacci; | |
})(); | |
memoizedFib(30); | |
// memoization without IIFE | |
const memoFib = () => { | |
let cache = {}; | |
return function fibonacci(value) { | |
if (value in cache) { | |
return cache[value]; | |
}else { | |
if (value <= 1) { | |
cache[value] = value; | |
return value; | |
} else { | |
cache[value] = fibonacci(value - 1) + fibonacci(value - 2) | |
return cache[value] | |
} | |
} | |
} | |
} | |
const fib0 = memoFib() | |
fibo(30); | |
// reusable memoization function | |
const memoize = callback => { | |
const cache = {} | |
return (...args) => { | |
if (cache[args]) { | |
return cache[args] | |
}else { | |
cache[args] = callback(...args); | |
return cache[args] | |
} | |
} | |
}; | |
const fabonacci = memoize((value)=> { | |
if (value <= 1) { | |
return value; | |
} | |
return fib(value - 1) + fib(value - 2); | |
}) | |
fabonacci(30); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment