Skip to content

Instantly share code, notes, and snippets.

@Hoxtygen
Created August 6, 2020 21:57
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 Hoxtygen/bd17bb3675a0100669dd380ba8924e52 to your computer and use it in GitHub Desktop.
Save Hoxtygen/bd17bb3675a0100669dd380ba8924e52 to your computer and use it in GitHub Desktop.
//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