Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Math.max, etc. as higher-order functions

In short, this works:

[1, 2, 3].reduce(function (a, b) { return Math.max(a, b); });
=> 3

But this doesn't:

[1, 2, 3].reduce(Math.max);
=> NaN

Pure puzzlement.

This is in Firefox 3.5.9, which I presume is using the mozilla standard implementation of reduce, FWIW.

like image 223
cemerick Avatar asked May 18 '10 11:05

cemerick


People also ask

What makes a function a higher-order function?

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

What is a higher-order functions give three examples?

Note: Functions such as filter(),map(),reduce(),some() etc, these all are example of Higher-Order Functions.

What is a higher-order function give any two examples?

Let's look at an example of a higher order functionconst numbers = [1, 2, 3, 4, 5]; function addOne(array) { for (let i = 0; i < array. length; i++) { console. log(array[i] + 1); } } addOne(numbers); The function addOne() accepts an array, adds one to each number in the array, and displays it in the console.


1 Answers

Math.max can be used as a higher-order function. The problem is .reduce will call the function with 4 arguments:

Math.max(accumulator, value, index, the_array)

here is the_array is an array, so Math.max returns NaN. I don't think there's simpler way to discard the last 2 arguments.

like image 150
kennytm Avatar answered Sep 21 '22 20:09

kennytm