Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ExtJS want to test if browser supports sorting?

I'am a javascript newbie, here is code from ExtJS which confuses me:

supportsSort = (function() {
    var a = [1,2,3,4,5].sort(function(){ return 0; });
    return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
}()),

Is someone can tell me why ExtJS want to do this test?

It is better to attach some examples code.

like image 315
hsy0 Avatar asked Sep 14 '13 16:09

hsy0


1 Answers

Hesitant to post this as the answer as I'm admittedly just taking an educated guess but according to MDN, the browser-compatibility for Array.sort is listed as ECMAScript5 and "yes" for everything (as opposed to listing actual version numbers) - leaving a test for actual support more or less redundant.

The variable name is probably a little bit miss-leading though because if you actually follow what it's doing, the function that is passed to sort is just returning 0; typically you might return 1 or -1 depending on your comparison conditions in order to manipulate the order of the array - so by doing this the expected result is that the order of the array remains unchanged.

The return statement is just a chain of boolean checks as to whether the array is still in the same order as it was initially. Arguably then this supportsSort flag is there to check whether or not the browser/Javascript's implementation of the sort function is in fact a stable algorithm.

like image 115
Emissary Avatar answered Nov 19 '22 23:11

Emissary