refactor: cleanups
[benchmarks-js.git] / max.mjs
CommitLineData
f522d7b9 1import Benchmark from 'benny'
0c01f51c 2
95d31631 3import { generateRandomNumberArray } from './benchmark-utils.mjs'
8e5cf49d 4
bb578730
JB
5const size = 10000
6const testArray = generateRandomNumberArray(size)
8e5cf49d
JB
7
8/**
9 *
10 * @param values
47006ddf 11 * @returns
8e5cf49d
JB
12 */
13function loopMax (values) {
528db716 14 let maximum = -Infinity
8e5cf49d 15 for (const value of values) {
528db716 16 if (value > maximum) maximum = value
8e5cf49d 17 }
528db716 18 return maximum
8e5cf49d
JB
19}
20
21/**
22 *
23 * @param values
47006ddf 24 * @returns
8e5cf49d
JB
25 */
26function reduceTernaryMax (values) {
528db716
JB
27 return values.reduce(
28 (maximum, num) => (maximum > num ? maximum : num),
29 -Infinity
30 )
8e5cf49d
JB
31}
32
33/**
34 *
35 * @param values
47006ddf 36 * @returns
8e5cf49d
JB
37 */
38function reduceMathMax (values) {
528db716 39 return values.reduce((maximum, num) => Math.max(maximum, num), -Infinity)
8e5cf49d
JB
40}
41
42/**
43 *
44 * @param values
47006ddf 45 * @returns
8e5cf49d
JB
46 */
47function sortMax (values) {
48 return values.sort((a, b) => b - a)[0]
49}
50
51Benchmark.suite(
bb578730 52 `Max from ${size} numbers`,
8e5cf49d
JB
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 }),
fb341cfe 62 Benchmark.add('reduceMath.max', () => {
8e5cf49d
JB
63 reduceMathMax(testArray)
64 }),
65 Benchmark.add('sortMax', () => {
66 sortMax(testArray)
67 }),
68 Benchmark.cycle(),
69 Benchmark.complete(),
fb341cfe
JB
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 })
4aa2893a 73).catch(console.error)