Skip to content

Instantly share code, notes, and snippets.

@jacricelli
Created May 19, 2020 00:53
Show Gist options
  • Save jacricelli/7c5bc39be4ad2bf7dbc0fff509a60f56 to your computer and use it in GitHub Desktop.
Save jacricelli/7c5bc39be4ad2bf7dbc0fff509a60f56 to your computer and use it in GitHub Desktop.
Natural comparison
/**
* https://stackoverflow.com/a/15479354
*/
const naturalCompare = (a, b) => {
const ax = [];
const bx = [];
a.replace(/(\d+)|(\D+)/g, (_, $1, $2) => { ax.push([$1 || Infinity, $2 || '']); });
b.replace(/(\d+)|(\D+)/g, (_, $1, $2) => { bx.push([$1 || Infinity, $2 || '']); });
while (ax.length && bx.length) {
const an = ax.shift();
const bn = bx.shift();
const nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment