I'm attempting to build out a monkey-patched version of mergeSort but I'm running into errors every single time. I've ran through debugger a few times and it looks like everything is sorting properly until the last step where I jump to a line in a loader.js file.
Can anyone help me check this out? Thanks in advance!
Array.prototype.mergeSort = function(callback) {
if (this.length <= 1) return this;
if (!callback) {
callback = function(x, y) {
if (x > y) return -1;
else if (x < y) return 1;
else return 0;
};
}
const mid = Math.floor(this.length / 2);
const sortedLeft = this.slice(0, mid).mergeSort(callback);
const sortedRight = this.slice(mid).mergeSort(callback);
return sortedLeft.merge(sortedRight, callback);
};
Array.prototype.merge = function(arr, callback) {
let merged = [];
while (this.length > 0 || arr.length > 0) {
if (callback(this[0], arr[0]) < 0) {
merged.push(arr.shift());
break;
} else if (callback(this[0], arr[0]) >= 0) {
merged.push(this.shift());
break;
}
}
merged = merged.concat(this);
merged = merged.concat(arr);
return merged;
};
callback = ...part is effectively the same asreturn y - x;} else if (callback(this[0], arr[0]) >= 0) {is just an else statement when paired with the first if.return y - xdoes not handle strings whereas the OP's default comparison function does.localeCompareinstead.