Created
May 19, 2020 00:53
-
-
Save jacricelli/7c5bc39be4ad2bf7dbc0fff509a60f56 to your computer and use it in GitHub Desktop.
Natural comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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