someoneHere
someoneHere

Reputation: 353

What is the purpose of Math.max in the context of array.slice

I"m doing some w3 coding exercises, and one example gives this:

return array.slice(Math.max(array.length - n, 0));

What is the purpose of Math.max here. I know it gives the max value of the given parameters (length -n , 0). But, confused why you cannot just use array.length - n?

Upvotes: 3

Views: 993

Answers (5)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

Since we do not know the context of n, it could be possible that n is larger than array.length. For instance if the array has length 4, n could be 5. Now a peculiar thing happens when the argument of .slice is strictly negative:

$ node
> x=[1,2,3,4]
[ 1, 2, 3, 4 ]
> x.slice(-1)
[ 4 ]

(using node, a JavaScript shell)

If the argument is -k, it retains the last k items. This can be undesired behavior. So using math.max one ensures the argument is positive and either no items are removed or the first l are removed with l being array.length-n.

Upvotes: 0

Oriol
Oriol

Reputation: 288470

This code produces a new array with the n last elements of arr.

However, n might be greater than the length of the array. In this case, Math.max ensures slice will be called with 0 instead of a negative number.

This might be problematic because when slice is called with a negative number, it adds the length of the array to it.

For example,

var array = [1, 2, 3],
    n = 4;
array.slice(array.length - n); // [3]
array.slice(Math.max(array.length - n, 0)); // [1, 2, 3]

Note this is only problematic if l < n < 2 l, where l is the length of the array.

  • If n <= l, then l - n >= 0. Math.max is not needed.
  • If n >= 2 l and n > 0, then l - n <= -n/2 < 0. Therefore slice will sum l, but 2 l - n is still not positive. Then slice will use 0. Math.max is not needed.
  • If n = 2 l = 0, then l - n = 0. Math.max is not needed.
  • If l < n < 2 l, then l - n < 0. Therefore slice will sum l, and 2 l - n > 0. Problem! Math.max is needed.

Upvotes: 0

RobertAKARobin
RobertAKARobin

Reputation: 4258

The Math.max here gives you the greater of array.length - n and 0.

array.length - n may be less than 0. Using a negative number would likely cause .slice to give you an unexpected result.

Thus, you are guaranteed to always be returned a "good" number.

Upvotes: 4

Mario Tacke
Mario Tacke

Reputation: 5498

Math.max returns the largest values from its parameters. In this case it looks like 0 is a default value and the author wanted to filter negative values since n can be greater than array.length.

Upvotes: 0

user1717828
user1717828

Reputation: 7223

If n is greater than array.length, the returned result will be negative. By saying return the greater value of this subtraction and zero, you make sure to never return a negative number.

Upvotes: 0

Related Questions