n
-th entry in the Fibonacci series.[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
forms the first ten entries of the Fibonacci series.fib(4) //--> 3
My Solution
function fib(n) {
if (n < 2) {
return n;
}
const resultsInverseQueue = [1, 0];
for (let i = 2; i <= n; i++) {
const earliest = resultsInverseQueue.pop();
resultsInverseQueue.unshift(resultsInverseQueue[0] + earliest);
// NOTE: could even be a one-liner
// resultsInverseQueue.unshift(resultsInverseQueue[0] + resultsInverseQueue.pop());
}
return resultsInverseQueue[0]
}
SG Solution
function memoize(fn) {
const cache = {};
return function(...args) {
if (cache[args]) {
return cache[args];
}
cache[args] = fn.apply(this, args);
return cache[args];
}
}
function slowFib(n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
const fib = memoize(slowFib);