jora
Version:
JavaScript object query engine
32 lines (26 loc) • 951 B
JavaScript
;
const stableSortSize = isSortStable(20) ? Infinity : isSortStable(10) ? 10 : 0;
function isSortStable(n) {
return Array.from({ length: n }, (_, idx) => ({ idx }))
.sort((a, b) => (a.idx % 2) - (b.idx % 2))
.every((a, idx) =>
idx < n / 2 ? (a.idx >> 1 === idx) : Math.ceil(n / 2) + (a.idx >> 1) === idx
);
}
function stableSort(array, cmp) {
// check size, e.g. old v8 had stable sort only for arrays with length less or equal 10
if (array.length <= stableSortSize) {
return array.slice().sort(cmp);
}
return array
.map((value, idx) => ({ value, idx }))
.sort((a, b) =>
(a.value === undefined
? b.value !== undefined
: b.value === undefined
? -1
: cmp(a.value, b.value)) || (a.idx - b.idx)
)
.map(item => item.value);
}
exports.stableSort = stableSort;