# Define a JavaScript function called max using Array.prototype.reduce

### Define a function called max that calculates the max number using Array.prototype.reduce.¶

In [2]:
function max(...args){
return args.reduce((acc, x) => acc > x ? acc : x, -Infinity)
}


### Generate some random data to test against Math.max.¶

In [3]:
function range(start, stop, step=1){
if(step < 1) throw new Error('step must be 1 or greater.');
if(stop <= start) throw new Error('stop must be larger than start');
return Array.from({length: ((stop - start) / step)}, (_, i) => start + (i * step));
}

In [4]:
function getRandomInt(min, max) {
return Math.floor((Math.random() * (max - min)) + min);
}

In [5]:
const [START, STOP] = [-1000, 1000],
test_data = range(0, 10)
.map(() => range(0, getRandomInt(1, 20))
.map(() => getRandomInt(START, STOP)));
console.log(test_data.slice(0, 5));

[
[
591,  992,  191, -305,
-428,  518,  541, -114,
-537, -486, -163, -629,
-489, -599, -484,  -73
],
[ 958, -381, -799, 536, -939, 721 ],
[ -149 ],
[ -284 ],
[ -989, 370, -831, -404, 204 ]
]


### Verify that the max value was found in each array using Math.max as the standard.¶

In [6]:
test_data.every(array => max(...array) === Math.max(...array));

Out[6]:
true