Thread: Maximum value in an array View Single Post
11-21-2012, 10:15 AM   PM User | #8
rnd me
Senior Coder

Join Date: Jun 2007
Location: Urbana
Posts: 3,970
Thanks: 10
Thanked 534 Times in 516 Posts
Quote:
 Originally Posted by felgall Just one extra point - If you use 0 as the second parameter in the bind for Math.max.apply then you eliminate the possibility of the maximum being negative. That second parameter should be Number.NEGATIVE_INFINITY in order to allow the maximum to be negative.
aw man, you shoulda stopped while you're ahead; you got the ball rollin on this. i did cover the 2nd arg implications in my follow-up to Dormilich's note. or, i should say, i tried...

the 2nd param to bind (in the case of Math.max) is ignored completely, so negatives work using 0 as well as false, {}, or [/rx/]; anything goes except nothing.

proof is easy, just use set of negatives to test your hypothesis:

Code:
var max=Math.max.apply.bind(Math.max, 0);
var myMax= max([-4,-7,-2,-55,-2,-12]) ;

alert( myMax ); // shows "-2"
-2 is the largest numeral in the set, so this code immediately falsifies your hypothesis that the use of "0 as the second parameter in the bind for Math.max.apply ... eliminate(s) the possibility of the maximum being negative" (emphasis mine).

try something less confusing; using garbage for this, and a different apply:

Code:
var max=isNaN.apply.bind(Math.max, {a:1});
var myMax= max([-4,-7,-2,-55,-2,-12]) ;

alert( myMax ); // shows "-2"
still works. if a function doesn't use this, as Math.max doesn't, this doesn't matter.
__________________
my site (updated 13/9/26)
BROWSER STATS [% share] (2013/10/31) IE7:0.5, IE8:8.6, IE9:5.3, IE10:12.3, FF:17.7, CH:41.8, SF:8.1, MOBILE:20.4

Last edited by rnd me; 11-21-2012 at 10:17 AM..