Skip to content

Instantly share code, notes, and snippets.

@lydell
Last active Apr 25, 2020
Embed
What would you like to do?
A stableSort function that uses plain .sort if stable
// 11 and 513 come from here: https://mathiasbynens.be/demo/sort-stability
function checkStable(length) {
return Array.apply(null, { length: length })
.map(function (_, i) {
return i;
})
.sort(function () {
return 0;
})
.every(function (n, i, a) {
return i === 0 || a[i - 1] === n - 1;
});
}
var stable11 = undefined;
var stable513 = undefined;
function stableSort(a, f) {
if (a.length < 11) {
a.sort(f);
} else if (a.length < 513) {
if (stable11 === undefined) {
stable11 = checkStable(11);
}
if (stable11) {
a.sort(f);
} else {
whateverStableSortImplementation(a, f);
}
} else {
if (stable513 === undefined) {
stable513 = checkStable(513);
}
if (stable513) {
a.sort(f);
} else {
whateverStableSortImplementation(a, f);
}
}
}
function whateverStableSortImplementation(a, f) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment