UNPKG

1.36 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = naturalCompare;
7
8/**
9 * Returns a number indicating whether a reference string comes before, or after,
10 * or is the same as the given string in natural sort order.
11 *
12 * See: https://en.wikipedia.org/wiki/Natural_sort_order
13 *
14 */
15function naturalCompare(aStr, bStr) {
16 var aIdx = 0;
17 var bIdx = 0;
18
19 while (aIdx < aStr.length && bIdx < bStr.length) {
20 var aChar = aStr.charCodeAt(aIdx);
21 var bChar = bStr.charCodeAt(bIdx);
22
23 if (isDigit(aChar) && isDigit(bChar)) {
24 var aNum = 0;
25
26 do {
27 ++aIdx;
28 aNum = aNum * 10 + aChar - DIGIT_0;
29 aChar = aStr.charCodeAt(aIdx);
30 } while (isDigit(aChar) && aNum > 0);
31
32 var bNum = 0;
33
34 do {
35 ++bIdx;
36 bNum = bNum * 10 + bChar - DIGIT_0;
37 bChar = bStr.charCodeAt(bIdx);
38 } while (isDigit(bChar) && bNum > 0);
39
40 if (aNum < bNum) {
41 return -1;
42 }
43
44 if (aNum > bNum) {
45 return 1;
46 }
47 } else {
48 if (aChar < bChar) {
49 return -1;
50 }
51
52 if (aChar > bChar) {
53 return 1;
54 }
55
56 ++aIdx;
57 ++bIdx;
58 }
59 }
60
61 return aStr.length - bStr.length;
62}
63
64var DIGIT_0 = 48;
65var DIGIT_9 = 57;
66
67function isDigit(code) {
68 return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9;
69}