3
\$\begingroup\$

Given is an array which contains sub-arrays. The elements in this sub-arrays are numbers.

The task is to implement a JavaScript-function which returns an array with the smallest / largest numbers in the single arrays.

I have figured out this solution:

// Returns the smallest / largest
//   numbers contained in a 
//   set of arrays.

// Parameter ---------------------
// 1.: Array - Containing other arrays.
// 2.: Function - Either Math.max or
//  Math.min

// Return -------------------------
// Array - Containing numbers in case
//  of success. 
//  Containing 'undefined' in case 
//  of elements which aren't arrays.
//  Containing NaN in case of elements 
//  which aren't numbers.

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct.apply(null, value);
    }
  });

  return ret;
}

Complete code (with examples) on CodePen: http://codepen.io/mizech/pen/bEBMaW?editors=101

Are there better ways to solve the described task?

\$\endgroup\$
1
\$\begingroup\$

Edge cases

Your function works slightly different than you say it does:

Math.max and Math.min work on anything that can be converted to a number. The array [1,2,"3",4] will just work fine. NaN is returned for a case whenever there is an element in that subarray that cannot be converted to a number.

Math.max and Math.min return -Infinity and Infinity if the array is empty. This case is undocumented.

Documentation

Your function is documented well. You might want to consider changing the documentation to the format that JSDoc uses, so you can automatically generate documentation for your javascript codebase.

\$\endgroup\$
0
2
\$\begingroup\$

I shoudn't be able to think to this elegant and concise solution by myself! Notably because till now I didn't pay great attention to some of the acute features of JS.

So it was for me the opportunity to examine them deeper. From this I notice a possible little improvement, by slightly reducing the code, like this:

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct(...value);
    }
  });

  return ret;
}

Here is the working modified example: http://codepen.io/anon/pen/obYMmQ?editors=101.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.