UNPKG

772 BJavaScriptView Raw
1// adapted from http://nedbatchelder.com/blog/200712.html#e20071211T054956
2
3var NUMBER_PATTERN = /([0-9]+)/;
4
5function naturalCompare(value1, value2) {
6 var keys1 = ('' + value1).split(NUMBER_PATTERN).map(tryParseInt);
7 var keys2 = ('' + value2).split(NUMBER_PATTERN).map(tryParseInt);
8 var key1;
9 var key2;
10 var compareFirst = Math.min(keys1.length, keys2.length);
11 var i, l;
12
13 for (i = 0, l = compareFirst; i < l; i++) {
14 key1 = keys1[i];
15 key2 = keys2[i];
16
17 if (key1 != key2) {
18 return key1 > key2 ? 1 : -1;
19 }
20 }
21
22 return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1);
23}
24
25function tryParseInt(value) {
26 return ('' + parseInt(value)) == value ?
27 parseInt(value) :
28 value;
29}
30
31module.exports = naturalCompare;