-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
max.mjs
74 lines (66 loc) · 1.23 KB
/
max.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
import { bench, group, run } from 'tatami-ng'
import { generateRandomNumberArray } from './benchmark-utils.mjs'
const size = 10000
const testArray = generateRandomNumberArray(size)
/**
*
* @param values
* @returns
*/
function loopMax (values) {
let maximum = Number.NEGATIVE_INFINITY
for (const value of values) {
if (value > maximum) maximum = value
}
return maximum
}
/**
*
* @param values
* @returns
*/
function reduceMathMax (values) {
return values.reduce(
(maximum, num) => Math.max(maximum, num),
Number.NEGATIVE_INFINITY
)
}
/**
*
* @param values
* @returns
*/
function reduceTernaryMax (values) {
return values.reduce(
(maximum, num) => (maximum > num ? maximum : num),
Number.NEGATIVE_INFINITY
)
}
/**
*
* @param values
* @returns
*/
function sortMax (values) {
return values.sort((a, b) => b - a)[0]
}
group(`Max from ${size} numbers`, () => {
bench('Math.max', () => {
Math.max(...testArray)
})
bench('loopMax', () => {
loopMax(testArray)
})
bench('reduceTernaryMax', () => {
reduceTernaryMax(testArray)
})
bench('reduceMathMax', () => {
reduceMathMax(testArray)
})
bench('sortMax', () => {
sortMax(testArray)
})
})
await run({
units: true,
})