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