News for hackers. Stuff that matters.
Re:Fast JavaScript Max/Min by jacobolus on Monday March 28, 2011 @01:38AM (#2377277)
Underscore.js is pretty good about delegating to built-in functions when available in its little utility functions. http://documentcloud.github.com/underscore/docs/underscore.h...
Re:Fast JavaScript Max/Min by jashkenas on Monday March 28, 2011 @07:33AM (#2377961)
The real reason why Underscore doesn't use "Math.max.apply" and "Math.min.apply", is that they only work on small arrays of numbers. After you get beyond 40-50,000-ish (last time I checked), some browsers will throw an exception because you can't pass that many arguments to a function.

I remember running into this in real-world code, trying to calculate the brightest pixel in a <canvas> imageData array.

Re:Fast JavaScript Max/Min by tzury on Monday March 28, 2011 @02:21AM (#2377373)
They surely missed this one though.

as Underscore.js do this:

     _.max = function(obj, iterator, context) {
        if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
        var result = {computed : -Infinity};
        each(obj, function(value, index, list) {
          var computed = iterator ? iterator.call(context, value, index, list) : value;
          computed >= result.computed && (result = {value : value, computed : computed});
        });
        return result.value;
     };


     _.min = function(obj, iterator, context) {
        if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
        var result = {computed : Infinity};
        each(obj, function(value, index, list) {
          var computed = iterator ? iterator.call(context, value, index, list) : value;
          computed < result.computed && (result = {value : value, computed : computed});
        });
        return result.value;
     };

While John do that:

    Array.max = function( array ){
      return Math.max.apply( Math, array );
    };
    Array.min = function( array ){
      return Math.min.apply( Math, array );
    };
Re:Fast JavaScript Max/Min by alunny on Monday March 28, 2011 @02:36AM (#2377404)
The Underscore functions do exactly the same as Resig's in the simple case (when passed just an array of numbers). They're longer because they accept custom iterators for non-numerical arrays.