Refactor generateRandomFloat() helper
[benchmarks-js.git] / fibonacci.js
1 const Benchmark = require('benny')
2
3 const number = 30
4
5 /**
6 * @param num
7 * @returns
8 */
9 function fibonacciLoop (num) {
10 let a = 1
11 let b = 0
12 let temp
13
14 while (num >= 0) {
15 temp = a
16 a = a + b
17 b = temp
18 num--
19 }
20
21 return b
22 }
23
24 /**
25 * @param num
26 * @returns
27 */
28 function fibonacciRecursion (num) {
29 if (num <= 1) return 1
30
31 return fibonacciRecursion(num - 1) + fibonacciRecursion(num - 2)
32 }
33
34 /**
35 * @param num
36 * @param memo
37 * @returns
38 */
39 function fibonacciRecursionMemoization (num, memo) {
40 memo = memo || {}
41
42 if (memo[num]) return memo[num]
43 if (num <= 1) return 1
44
45 return (memo[num] =
46 fibonacciRecursionMemoization(num - 1, memo) +
47 fibonacciRecursionMemoization(num - 2, memo))
48 }
49
50 Benchmark.suite(
51 `Fibonacci number ${number}`,
52 Benchmark.add('fibonacciLoop', () => {
53 fibonacciLoop(number)
54 }),
55 Benchmark.add('fibonacciRecursion', () => {
56 fibonacciRecursion(number)
57 }),
58 Benchmark.add('fibonacciRecursionMemoization', () => {
59 fibonacciRecursionMemoization(number)
60 }),
61 Benchmark.cycle(),
62 Benchmark.complete(),
63 Benchmark.save({ file: 'fibonacci', format: 'json', details: true }),
64 Benchmark.save({ file: 'fibonacci', format: 'chart.html', details: true }),
65 Benchmark.save({ file: 'fibonacci', format: 'table.html', details: true })
66 )