Chaining Function.apply.bind() in Return Largest Number in Arrays

I had no idea it works before looking at this but I thought I’d take a shot at this, too, as a learning exercise!

After much reading, I believe all the answers can actually be found in the MDN documentation. Have a look here and pay attention to the definition and the examples partially applied functions and creating shortcuts for bind(). Also have a look here regarding the Function constructor.

Going back to the code from the advanced solution:

function largestOfFour ( arr ) {
return arr.map ( Function.apply.bind ( Math.max, null ));
}

I believe the idea is to create a partially applied function so that it can be used with the map() method. With reference to the creating shortcuts section of the MDN documentation for bind(), Function.apply.bind(Math.max, null)) effectively creates a shortcut to Math.max.apply(null, ...), where ... are arguments waiting to be supplied, which will be an array because of map() (hence a partial function).

I think the advanced solution is functionally the same as the following code (tested on CodePen), which is probably easier to understand (at least for me it is):

var shortcut = function(subArray) {
    return Math.max.apply(null, subArray);
}

function largestOfFour(arr) {
    return arr.map(shortcut);
}

I hope that helps!

EDIT Typo!

2 Likes