1 |
|
2 |
|
3 | var NUMBER_PATTERN = /([0-9]+)/;
|
4 |
|
5 | function 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 |
|
25 | function tryParseInt(value) {
|
26 | return ('' + parseInt(value)) == value ?
|
27 | parseInt(value) :
|
28 | value;
|
29 | }
|
30 |
|
31 | module.exports = naturalCompare;
|