These are chat archives for camperbot/bonfire-return-largest-numbers-in-arrays

17th
Nov 2015
Yosafat Ariel
@yoskakomba
Nov 17 2015 02:08
hint
CamperBot
@camperbot
Nov 17 2015 02:08

hint [8/8]

Solution 2:

function largestOfFour(arr) {
  // You can do this!
  // Yes, I can. :P
  return arr.map(Function.apply.bind(Math.max, null));
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Code Explanation:

  • The Function.apply.bind(Math.max, null) makes a new function accepting the arr.map values i.e. the inner arrays.

Now the new function needs to find the max of the input inner array.

  • So we want to create a function that does the work of Math.max and accepts input as an array.

e.g. wouldn't be nice if the Math.max would be accepting inputs like this:
Math.max([9, 43, 20, 6]); // 43.

  • To do the work of accepting params as array, there is this Function.apply method but it invokes the context function.

i.e. Math.max.apply(null, [9, 43, 20, 6]); // 43 would invoke the Max.max method.

Here we're passing null as the context of the Function.apply method as Math.max doesn't need any context.

But that's not useful for arr.map which accepts a function value. So we create a function value using Function.bind method.

  • Since, Function.apply is a static method of Function Object, so we can call Function.prototype.bind on Function.apply i.e. Function.apply.bind.

Now we pass the context for Function.apply.bind call i.e. Math.max method as the 1st argument which would give us the functionality of Math.max method.

  • Since Function.apply method takes a context as it's 1st argument, hence, we need to pass a bogus context for Function.apply method.
    • So, we pass null as the 2nd param to Function.apply.bind which gives a context to the Math.max method.
    • Since, Math.max is independent of any context, hence, it ignores the bogus context given by Function.apply method call.

So in the end we get a function (using Function.bind method) that works like Math.max but accepts params as an array like Function.apply :smiley:

comprendido? :neutral_face:

NOTE: This is an advanced solution. NOT FOR BEGINNERS.

Reference:-

Credits:

If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @Rafase282 @abhisekp

NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)

type hint for next hint :pencil: [Contribute at the FCC Wiki]