build(deps-dev): apply updates
[benchmarks-js.git] / fibonacci.mjs
1 import { bench, group, run } from 'tatami-ng'
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 tmp = current
29 current += previous
30 previous = tmp
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 group(`Fibonacci number ${number}`, () => {
61 bench('fibonacciLoop', () => {
62 fibonacciLoop(number)
63 })
64 bench('fibonacciLoopWhile', () => {
65 fibonacciLoopWhile(number)
66 })
67 bench('fibonacciRecursion', () => {
68 fibonacciRecursion(number)
69 })
70 bench('fibonacciRecursionMemoization', () => {
71 fibonacciRecursionMemoization(number)
72 })
73 })
74
75 await run({
76 units: true
77 })