Array.prototype.max and Array.prototype.min

Xavier MONTILLET xavierm02.net at gmail.com
Mon Feb 20 11:25:23 PST 2012


Hi,

I think it'd be nice to have Array.prototype.max and Array.prototype.min.

What they would do is this:

Array.prototype.max = function ( f ) {
    return this.sort( f )[ this.length - 1 ];
};
Array.prototype.min = function ( f ) {
    return this.sort( f )[ 0 ];
};

Of course, that's not how they would actually be implemented (sorting
the whole array to get the max/minimum is ridiculous) but I wrote them
that way so that we clearly see the behavior when a function is given
as argument: just as with Array.prototype.sort, the function is used
instead of < in the comparisons.

Here is a more efficient implementation:

Array.prototype.max = function ( f ) {
    var max = this[ 0 ];
    var i;
    var l = this.length;
    var item;
    if ( f ) {
        for ( i = 1; i < l; ++i ) {
            item = this[ i ];
            if ( item > max ) {
                max = item;
            }
        }
    } else {
        for ( i = 1; i < l; ++i ) {
            item = this[ i ];
            if ( f( item, max ) === 1 ) {// maybe it should be -1... I
never remember...
                max = item;
            }
        }
    }
    return max;
};


More information about the es-discuss mailing list