0

I have the following function

function min() {
  var array = Array.prototype.slice.call(arguments);
  array = array.length === 1 && isNumeric(array[0].length) ? array[0] : array;

  var min = array[0];
  var i, count;
  for (i = 1, count = array.length; i < count; i++) {
    if (array[i] < min) min = array[i];
  }
  return min;
},

I don't understand why the following line was placed in, what is its purpose?

array = array.length === 1 && isNumeric(array[0].length) ? array[0] : array;
1
  • That whole function seems way too complicated when you can just call Math.min.apply(null, arrayOfNumbers) OR Math.min.call(null, num1, num2, num3) Commented May 5, 2016 at 15:02

4 Answers 4

3
  • condition ? returnIfTrue : returnIfFalse is called a ternary operator.
  • array.length === 1 && isNumeric(array[0].length) means "If array has a single element and that first element is itself an Array".
  • a = ternaryOperator means set a to the result of the ternary operator.

These three together mean that you can call min in two ways:

min(1, 2, 3) or min([1, 2, 3]).

Sign up to request clarification or add additional context in comments.

Comments

2

That line allows passing numbers directly as arguments or passing a single array as the first argument:

min(1,2,3);
min([1,2,3]);

Comments

1

I would refactor this function into

var min = (...args) => Array.isArray(args[0]) ? Math.min(...args[0]) : Math.min(...args);

document.write("<pre>" + min([1,2,3,4,-1]) + "</pre>");
document.write("<pre>" + min(1,2,-3,4,-1) + "</pre>");

2 Comments

Arrow functions are a bit of a stretch here. Browser support is not really there yet.
True.. Safari doesn't support arrows but i just wanted to demonstrate the idea. It's no big deal to implement the same thing in conventional ways. It's also worth to notice that exactly the same ...args syntax work both as rest and spread operator.
-1

Your code is confusing, try doing something like this

var min = 1000000;
 var temp = 0;
if ( element < min){
 temp = element; 
 min = element;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.