Comparing Fibonacci
by Peer Reynders
HTML
<html>
<head>
<title>Comparing Fibonacci</title>
<meta charset="UTF-8" />
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>Note:</h1>
<p>Just a JavaScript script—not a web page.</p>
<p>Check the "Console" tab.</p>
</body>
</html>
JavaScript
const locales = !navigator
? []
: Array.isArray(navigator.languages)
? navigator.languages
: typeof navigator.language === 'string'
? navigator.language
: [];
const fmt = new Intl.NumberFormat(locales, { maximumFractionDigits: 0 });
function report(n, fn) {
const t0 = performance.now();
const result = fn(n);
const t1 = performance.now();
return `f(${n}): ${result} (${fmt.format(t1 - t0)} ms)`;
}
const fibo = (n) => {
if (n <= 1) {
return n;
}
return fibo(n - 1) + fibo(n - 2);
};
function fib(num) {
const n = num >= 0 ? Math.floor(num) : 0
if (n < 2) return n;
if (n > 78) throw new Error(`fib(${num}) would exceed Number.MAX_SAFE_INTEGER`);
let fn = 1;
for (let fn1 = 0, i = n - 1; i > 0; [fn1, fn] = [fn, fn1 + fn], i -= 1);
return fn;
}
const n = 42;
console.log(report(n ,fibo));
console.log(report(n, fib));