30 lines
701 B
JavaScript
30 lines
701 B
JavaScript
|
module.exports = function naturalCmp(str1, str2) {
|
||
|
if (str1 == str2) return 0;
|
||
|
if (!str1) return -1;
|
||
|
if (!str2) return 1;
|
||
|
|
||
|
var cmpRegex = /(\.\d+|\d+|\D+)/g,
|
||
|
tokens1 = String(str1).match(cmpRegex),
|
||
|
tokens2 = String(str2).match(cmpRegex),
|
||
|
count = Math.min(tokens1.length, tokens2.length);
|
||
|
|
||
|
for (var i = 0; i < count; i++) {
|
||
|
var a = tokens1[i],
|
||
|
b = tokens2[i];
|
||
|
|
||
|
if (a !== b) {
|
||
|
var num1 = +a;
|
||
|
var num2 = +b;
|
||
|
if (num1 === num1 && num2 === num2) {
|
||
|
return num1 > num2 ? 1 : -1;
|
||
|
}
|
||
|
return a < b ? -1 : 1;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (tokens1.length != tokens2.length)
|
||
|
return tokens1.length - tokens2.length;
|
||
|
|
||
|
return str1 < str2 ? -1 : 1;
|
||
|
};
|