I am trying to create a stable sort element to the default JavaScript .sort() function. I have it working in all browsers except for IE11 and below.
Here is the code:
Array.prototype.stableSort = function(cmp) {
cmp = !!cmp ? cmp : (function(a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
let stabilizedThis = this.map(function(el, index) { return [el, index]; });
stabilizedThis.sort(function(a, b) {
let order = cmp(a[0], b[0]);
if (order != 0) return order;
return a[1] - b[1];
});
for (let i=0; i<this.length; i++) {
this[i] = stabilizedThis[i][0];
}
return this;
}
For reference, the above code fails even when I am not actually using this stable sort functionality in my code. My usage will be something like this:
sortedArray.stableSort(function(a,b) {
if (type == "string") {
return a[index]["value"].toString().localeCompare(b[index]["value"].toString());
}
else if (type == "number") {
return a[index]["value"] - b[index]["value"];
}
});
Note: to narrow done the issue, I have discovered that -- at a minimum, this code works in IE11:
Array.prototype.stableSort = function(cmp) {
cmp = !!cmp ? cmp : (function(a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
// everything here was removed for testing
return this;
}
Of course this does not sort (or stable sort), but it does not cause a syntax error.
Unfortunately, the development tools and console does not give me an indication of the line number where the failure is.
For reference, I am basing my code off of what I found at this link. They were using stuff that wasn't compatible with ES5 (IE11's limit) so I had to change it up a bit. Not sure if I missed something else with this.
Any ideas on what is happening?
Microsoft IE11 does not support ES6, like let
statements.
You could replace it with var
statements.
Array.prototype.stableSort = function (cmp) {
cmp = cmp ||function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
var stabilizedThis = this.map(function (el, index) { return [el, index]; });
stabilizedThis.sort(function (a, b) {
return cmp(a[0], b[0]) || a[1] - b[1];
});
for (var i = 0; i < this.length; i++) {
this[i] = stabilizedThis[i][0];
}
return this;
}