build: fix lint-staged configuration
[benchmarks-js.git] / fibonacci.mjs
CommitLineData
f522d7b9 1import Benchmark from 'benny'
a9c78d5d
JB
2
3const number = 30
4
5/**
6 * @param num
7fd91296 7 * @returns
a9c78d5d
JB
8 */
9function fibonacciLoop (num) {
b34f63ab
JB
10 const fib = []
11 fib[0] = 0
12 fib[1] = 1
13 for (let i = 2; i <= num; i++) {
14 fib[i] = fib[i - 2] + fib[i - 1]
a9c78d5d 15 }
b34f63ab 16 return fib[num]
a9c78d5d
JB
17}
18
ddcd2a7a
JB
19/**
20 *
21 * @param num
22 * @returns
23 */
24function fibonacciLoopWhile (num) {
25 let current = 1
26 let previous = 0
27 while (--num) {
28 const temp = current
29 current += previous
30 previous = temp
31 }
32 return current
33}
34
a9c78d5d
JB
35/**
36 * @param num
7fd91296 37 * @returns
a9c78d5d
JB
38 */
39function fibonacciRecursion (num) {
b34f63ab 40 if (num <= 1) return num
a9c78d5d
JB
41 return fibonacciRecursion(num - 1) + fibonacciRecursion(num - 2)
42}
43
44/**
45 * @param num
46 * @param memo
7fd91296 47 * @returns
a9c78d5d
JB
48 */
49function fibonacciRecursionMemoization (num, memo) {
50 memo = memo || {}
51
52 if (memo[num]) return memo[num]
b34f63ab 53 if (num <= 1) return num
a9c78d5d
JB
54
55 return (memo[num] =
56 fibonacciRecursionMemoization(num - 1, memo) +
57 fibonacciRecursionMemoization(num - 2, memo))
58}
59
662a730a 60Benchmark.suite(
bb578730 61 `Fibonacci number ${number}`,
662a730a 62 Benchmark.add('fibonacciLoop', () => {
a9c78d5d 63 fibonacciLoop(number)
662a730a 64 }),
ddcd2a7a
JB
65 Benchmark.add('fibonacciLoopWhile', () => {
66 fibonacciLoopWhile(number)
67 }),
662a730a 68 Benchmark.add('fibonacciRecursion', () => {
a9c78d5d 69 fibonacciRecursion(number)
662a730a
JB
70 }),
71 Benchmark.add('fibonacciRecursionMemoization', () => {
a9c78d5d 72 fibonacciRecursionMemoization(number)
662a730a
JB
73 }),
74 Benchmark.cycle(),
75 Benchmark.complete(),
76 Benchmark.save({ file: 'fibonacci', format: 'json', details: true }),
77 Benchmark.save({ file: 'fibonacci', format: 'chart.html', details: true }),
78 Benchmark.save({ file: 'fibonacci', format: 'table.html', details: true })
48f5216d 79).catch((err) => {
4b16770a
JB
80 console.error(err)
81})