-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.mjs
77 lines (68 loc) · 1.32 KB
/
fibonacci.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { bench, group, run } from 'tatami-ng'
const number = 30
/**
* @param num
* @returns
*/
function fibonacciLoop (num) {
const fib = []
fib[0] = 0
fib[1] = 1
for (let i = 2; i <= num; i++) {
fib[i] = fib[i - 2] + fib[i - 1]
}
return fib[num]
}
/**
*
* @param num
* @returns
*/
function fibonacciLoopWhile (num) {
let current = 1
let previous = 0
while (--num) {
const tmp = current
current += previous
previous = tmp
}
return current
}
/**
* @param num
* @returns
*/
function fibonacciRecursion (num) {
if (num <= 1) return num
return fibonacciRecursion(num - 1) + fibonacciRecursion(num - 2)
}
/**
* @param num
* @param memo
* @returns
*/
function fibonacciRecursionMemoization (num, memo) {
memo = memo || {}
if (memo[num]) return memo[num]
if (num <= 1) return num
return (memo[num] =
fibonacciRecursionMemoization(num - 1, memo) +
fibonacciRecursionMemoization(num - 2, memo))
}
group(`Fibonacci number ${number}`, () => {
bench('fibonacciLoop', () => {
fibonacciLoop(number)
})
bench('fibonacciLoopWhile', () => {
fibonacciLoopWhile(number)
})
bench('fibonacciRecursion', () => {
fibonacciRecursion(number)
})
bench('fibonacciRecursionMemoization', () => {
fibonacciRecursionMemoization(number)
})
})
await run({
units: true,
})