Second arguments for Array.prototype.sort: map function

Brendan Eich brendan at mozilla.org
Tue Feb 28 03:05:14 PST 2012


Xavier MONTILLET wrote:
> Here's an example:
>
> var array = [ { v: 3.2 }, { v: 1.3 }, { v: 2.1 } ];
> var compare = function ( a, b ) {
>     return a - b;
> };
> var transform = function ( x ) {
>     return { v: x.v - Math.floor( x.v ) };
> };
>
> var sortedArray = array.sort( compare, transform );
>
> console.log( array.map( transform ) );// [ { v: .2 }, { v: .3 }, { v: 
> .1 } ]
> // you can see to sort it you need to take the last element and put it 
> at the beginning
> // so you do that on array:
> console.log( sortedArray );// [ {  v: 2.1 }, {v: 3.2 }, {v: 1.3 } ]
>
> So you sort the transformed array and you apply the exact same 
> modifications to the original .
>
> Is it clearer?
>

Yes, clear enough -- however adding new trailing arguments to an 
existing method is treacherous. It's likely calls in the wild pass a 
second argument by mistake. Less likely but still possible: an 
implementation has unwisely extended sort to have an optional second 
parameter already. This goes against the now-explicit NOTE in ES5:

NOTE Implementations that add additional capabilities to the set of 
built-in functions are encouraged to do so by adding new functions 
rather than adding new parameters to existing functions.

We could rule this out for the top five browser engines, but the 
possibility of extant code passing an extra actual parameter remains.

Better to have a new sortWithTransform method if necessary.

/be


More information about the es-discuss mailing list