What is the easiest way to find maximum and minimum of a given set of numbers?
Well, that’s easy.
1
2
3
4
|
console.log(Math.max(1, 3, 5));
console.log(Math.min(1, 3, 5));
// 5 1
|
How about an array?
The first thing that comes to mind..
1
2
3
4
5
6
7
8
9
|
const nums = [1, 3, 5];
const max = nums.reduce((n, mx) => (n > mx ? n : mx));
console.log("max: ", max);
const min = nums.reduce((n, mn) => (n < mn ? n : mn));
console.log("min: ", min);
// 5 1
|
But, an easier solution is right in front of us.
1
2
3
|
console.log(Math.max(...nums));
console.log(Math.min(...nums));
// 5 1
|
Moral of the story
Never trust the first instinct.
But, you are not likely to be as naΓ―ve as me - so YMMV.