UNPKG

jora

Version:

JavaScript object query engine

28 lines (24 loc) 909 B
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 ); } export 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); }