Skip to content

Instantly share code, notes, and snippets.

@kazu69
Created Jan 29, 2018
Embed
What would you like to do?
Fibonacci algorithm in Javascript

performance

general.js > memonize.js > simple-loop.js

const num = 20;
const fibonacci = (i) => {
const sqrt5 = Math.sqrt(5);
const phi = (sqrt5 + 1) / 2;
if (i < 2) {
return i;
}
return Math.round(Math.pow(phi, i) / sqrt5);
}
for (let i = 0; i < num; i++) {
const fib = fibonacci(i);
console.log(`result fib is ${fib}`);
}
const num = 20;
const fibonacci = () => {
const memo = [0, 1];
const fib = (i) => {
if (i < 0) {
return undefined;
}
if (typeof memo[i] === 'number') {
return memo[i];
}
if (i < 2) {
memo[i] = i;
} else {
memo[i] = fibonacci1(i - 1) + fibonacci1(i - 2);
}
return memo[i];
}
return fib;
}
for (let i = 0; i < num; i++) {
const fib = (fibonacci())(i);
console.log(`result fib is ${fib}`);
}
const num = 20;
const fibonacci = (i) => {
return (i < 2 ? i : fibonacci1(i -1) + fibonacci1(i - 2))
}
for (let i = 0; i < num; i++) {
const fib = fibonacci.call(null, i);
console.log(`result fib is ${fib}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment