Skip to content

Instantly share code, notes, and snippets.

@euank
Created April 24, 2013 08:41
Show Gist options
  • Save euank/5450654 to your computer and use it in GitHub Desktop.
Save euank/5450654 to your computer and use it in GitHub Desktop.
Open as html in firefox and chrome to see that the old sort function behaves incorrectly in firefox while the new one behaves correctly in both.
Old output:
<div id="oldoutput">
</div>
<br /><br />
New output:
<div id="newoutput">
</div>
<script>
var vcs = [{},
{"vcID":"0_1","line":"16"},
{},
{"vcID":"2_1","line":"10"},
{},
{"vcID":"3_1","line":"19"},
{"vcID":"3_2","line":"19"},
{"vcID":"3_3","line":"19"},
{"vcID":"3_4","line":"20"},
{},
{"vcID":"4_1","line":"23"}]
function sortByIdAndLine(a, b){
var line1 = parseInt(a.line,10);
var line2 = parseInt(b.line,10);
var id1 = a.vcID;
var id2 = b.vcID;
if(isNaN(line1) || isNaN(line2)) {
if(isNaN(line1)) return 1;
if(isNaN(line2)) return -1;
}
if(line1 < line2) return -1;
if(line1 > line2) return 1;
if(id1 < id2) return -1;
if(id1 > id2) return 1;
return 0;
}
function oldSortByIdAndLine(a, b){
var line1 = a.line;
var line2 = b.line;
var id1 = a.vcID;
var id2 = b.vcID;
return (((typeof line1 === "undefined") || (typeof line2 === "undefined"))? 1 : (
(line1 != line2) ? (
(line1 < line2) ? -1 : ((line1 > line2) ? 1 : 0)
) : (
(id1 < id2) ? -1 : ((id1 > id2) ? 1 : 0)
)
));
//return ((typeof line1 === "undefined") ? 1 : ((line1 < line2) ? -1 : ((line1 > line2) ? 1 : 0)));
}
vcs.sort(oldSortByIdAndLine);
for(var i=0;i<vcs.length;i++) {
document.querySelector("#oldoutput").innerHTML += vcs[i].vcID + " " + vcs[i].line + "<br />\n";
}
vcs.sort(sortByIdAndLine);
for(var i=0;i<vcs.length;i++) {
document.querySelector("#newoutput").innerHTML += vcs[i].vcID + " " + vcs[i].line + "<br />\n";
}
</script>
@Bekt
Copy link

Bekt commented Apr 25, 2013

Ternaries ftw!

function oldSortByIdAndLine(a, b){
    var line1 = a.line;
    var line2 = b.line;

    var id1 = a.vcID;
    var id2 = b.vcID;

    return (
        !line1 || !line2 ?
            !line1 ? 1 : -1 :
                line1 < line2 ? -1 : 
                    line1 > line2 ? 1 : 
                        id1 < id2 ? -1 :
                            id1 > id2 ? 1 : 0
    );

    //return ((typeof line1 === "undefined") ? 1 : ((line1 < line2) ? -1 : ((line1 > line2) ? 1 : 0)));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment