How to write array sort polyfill using merge sort approach
I was trying to write a Polyfill for array sorting in javascript. However it turns out that the comparator doesn't cause any effect on the Polyfill. Any ideas how to make it work?
const arrA = [2, 3, 4, 1, 2, 3, 1, 5, 6, 8, 5, 9, 3];
const newArr = [...new Set(arrA)];
Array.prototype.myNewSort = function(compareFn) {
return mergeSort(this);
function mergeSort(arr) {
if (arr.length <= 1)
return arr;
const mid = Math.floor(arr.length / 2);
const leftArr = arr.slice(0, mid);
const rightArr = arr.slice(mid);
return merge(mergeSort(leftArr), mergeSort(rightArr));
}
function merge(left, right) {
let newArr = [];
while (left.length > 0 && right.length > 0) {
let newCompareFn = compareFn ? compareFn = (l, r) => l < r : newCompareFn;
newCompareFn = (left, right) => left > right;
if (newCompareFn(left[0], right[0])) {
newArr.push(left.shift());
} else {
newArr.push(right.shift())
}
}
return [...newArr, ...left, ...right];
}
function composeCompareFn(compareResult) {
if (Math.sign(compareResult) === -1) return false;
if (Math.sign(compareResult) === 1) return true;
if (compareResult === 0) return false;
}
}
const sortedArr = newArr.myNewSort((a, b) => a - b);
console.log("sortedArr", sortedArr);