refactor: automatically sort imports
[benchmarks-js.git] / max.mjs
1 import Benchmark from 'benny'
2
3 import { generateRandomNumberArray } from './benchmark-utils.mjs'
4
5 const size = 10000
6 const testArray = generateRandomNumberArray(size)
7
8 /**
9 *
10 * @param values
11 * @returns
12 */
13 function loopMax (values) {
14 let maximum = -Infinity
15 for (const value of values) {
16 if (value > maximum) maximum = value
17 }
18 return maximum
19 }
20
21 /**
22 *
23 * @param values
24 * @returns
25 */
26 function reduceTernaryMax (values) {
27 return values.reduce(
28 (maximum, num) => (maximum > num ? maximum : num),
29 -Infinity
30 )
31 }
32
33 /**
34 *
35 * @param values
36 * @returns
37 */
38 function reduceMathMax (values) {
39 return values.reduce((maximum, num) => Math.max(maximum, num), -Infinity)
40 }
41
42 /**
43 *
44 * @param values
45 * @returns
46 */
47 function sortMax (values) {
48 return values.sort((a, b) => b - a)[0]
49 }
50
51 Benchmark.suite(
52 `Max from ${size} numbers`,
53 Benchmark.add('Math.max', () => {
54 Math.max(...testArray)
55 }),
56 Benchmark.add('loopMax', () => {
57 loopMax(testArray)
58 }),
59 Benchmark.add('reduceTernaryMax', () => {
60 reduceTernaryMax(testArray)
61 }),
62 Benchmark.add('reduceMath.max', () => {
63 reduceMathMax(testArray)
64 }),
65 Benchmark.add('sortMax', () => {
66 sortMax(testArray)
67 }),
68 Benchmark.cycle(),
69 Benchmark.complete(),
70 Benchmark.save({ file: 'max', format: 'json', details: true }),
71 Benchmark.save({ file: 'max', format: 'chart.html', details: true }),
72 Benchmark.save({ file: 'max', format: 'table.html', details: true })
73 ).catch(console.error)