Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active October 21, 2018 04:15
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 matsuby/18a1e273a0624af69a93205d7c5bea73 to your computer and use it in GitHub Desktop.
Save matsuby/18a1e273a0624af69a93205d7c5bea73 to your computer and use it in GitHub Desktop.
JavaScript one-liner function: fibonacci (get single fibonacci number)
// =========================================================================
// https://en.wikipedia.org/wiki/Fibonacci_number#List_of_Fibonacci_numbers
// =========================================================================
// for ES2015
{
const fibonacci = Object.assign(function f(n){return +n!==parseInt(n)||!isFinite(n)?NaN:Math.abs(n)>1476?Math.sign(n)*Infinity:(n>=0?1:~n%2?-1:1)*(f[Math.abs(n)]||(f[Math.abs(n)-1]=f(Math.abs(n)-1))+f[Math.abs(n)-2])},{"-2":-1,"-1":1,0:0,1:1});
const positiveIntegers = [...[...Array(21).keys()], 100, 999, 1476, 1477, 1478, 1479];
const negativeIntegers = positiveIntegers.map(c => -c);
const notIntegers = [true, false, "", null, undefined, NaN, Infinity, -Infinity, 0.5, -0.5];
for (p of [...positiveIntegers, ...negativeIntegers, ...notIntegers]) {
const t = isFinite(p) ? JSON.stringify(p) : p;
console.log(`${t} is ${fibonacci(p)}`);
}
}
// for ES2015
{
const fibonacciGenerator = function* (max=1476) {
for (let [i, current, next] = [0, 0, 1]; i < max; i++) {
yield current;
[current, next] = [next, current + next];
}
};
const fibonacciNumbers = [...fibonacciGenerator()];
console.log(JSON.stringify(fibonacciNumbers));
console.log(JSON.stringify("length: " + fibonacciNumbers.length));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment