Tuesday, July 21, 2020

When life gives you lemons, make functions

// You can't do this in Math.min and Math.max functions:
const arr = [20,10,30,40];

console.log(Math.min(arr));
console.log(Math.max(arr));

// You have to do this:
console.log(Math.min(20,10,30,40));
console.log(Math.max(20,10,30,40));

Output:
NaN
NaN
10
40

Whoever design the Math.min and Math.max functions must be thinking that devs know in advance how many items the user will create.

Here's how to pass array to Math.min and Math.max:
const arr = [20,10,30,40];

console.log(Math.min.apply(null, arr));
console.log(Math.max.apply(null, arr));

Output:
10
40

That's tedious if you need to do it often. Generate functions that accepts array out of Math.min and Math.max.
const getThe = [Math.min, Math.max].reduce((fns, f) => ({
    ...fns,
    [f.name]: Function.apply.bind(f, null)
}), {});



const arr = [20,10,30,40];

console.log(getThe.min(arr));
console.log(getThe.max(arr));


Output:
10
40

When life gives you syntactic sugar? Well, gulp them!
const arr = [20,10,30,40];

console.log(Math.min(...arr));
console.log(Math.max(...arr));

Output:
10
40

No comments:

Post a Comment