build: bump volta pnpm version
[benchmarks-js.git] / fibonacci.mjs
1 import Benchmark from 'benny'
2
3 const number = 30
4
5 /**
6 * @param num
7 * @returns
8 */
9 function fibonacciLoop (num) {
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]
15 }
16 return fib[num]
17 }
18
19 /**
20 *
21 * @param num
22 * @returns
23 */
24 function 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
35 /**
36 * @param num
37 * @returns
38 */
39 function fibonacciRecursion (num) {
40 if (num <= 1) return num
41 return fibonacciRecursion(num - 1) + fibonacciRecursion(num - 2)
42 }
43
44 /**
45 * @param num
46 * @param memo
47 * @returns
48 */
49 function fibonacciRecursionMemoization (num, memo) {
50 memo = memo || {}
51
52 if (memo[num]) return memo[num]
53 if (num <= 1) return num
54
55 return (memo[num] =
56 fibonacciRecursionMemoization(num - 1, memo) +
57 fibonacciRecursionMemoization(num - 2, memo))
58 }
59
60 Benchmark.suite(
61 `Fibonacci number ${number}`,
62 Benchmark.add('fibonacciLoop', () => {
63 fibonacciLoop(number)
64 }),
65 Benchmark.add('fibonacciLoopWhile', () => {
66 fibonacciLoopWhile(number)
67 }),
68 Benchmark.add('fibonacciRecursion', () => {
69 fibonacciRecursion(number)
70 }),
71 Benchmark.add('fibonacciRecursionMemoization', () => {
72 fibonacciRecursionMemoization(number)
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 })
79 ).catch(err => {
80 console.error(err)
81 })