1 |
|
---|
2 |
|
---|
3 |
|
---|
4 | /*
|
---|
5 | * @version 1.4.0
|
---|
6 | * @date 2015-10-26
|
---|
7 | * @stability 3 - Stable
|
---|
8 | * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
|
---|
9 | * @license MIT License
|
---|
10 | */
|
---|
11 |
|
---|
12 |
|
---|
13 | var naturalCompare = function(a, b) {
|
---|
14 | var i, codeA
|
---|
15 | , codeB = 1
|
---|
16 | , posA = 0
|
---|
17 | , posB = 0
|
---|
18 | , alphabet = String.alphabet
|
---|
19 |
|
---|
20 | function getCode(str, pos, code) {
|
---|
21 | if (code) {
|
---|
22 | for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
|
---|
23 | return +str.slice(pos - 1, i)
|
---|
24 | }
|
---|
25 | code = alphabet && alphabet.indexOf(str.charAt(pos))
|
---|
26 | return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
|
---|
27 | : code < 46 ? 65 // -
|
---|
28 | : code < 48 ? code - 1
|
---|
29 | : code < 58 ? code + 18 // 0-9
|
---|
30 | : code < 65 ? code - 11
|
---|
31 | : code < 91 ? code + 11 // A-Z
|
---|
32 | : code < 97 ? code - 37
|
---|
33 | : code < 123 ? code + 5 // a-z
|
---|
34 | : code - 63
|
---|
35 | }
|
---|
36 |
|
---|
37 |
|
---|
38 | if ((a+="") != (b+="")) for (;codeB;) {
|
---|
39 | codeA = getCode(a, posA++)
|
---|
40 | codeB = getCode(b, posB++)
|
---|
41 |
|
---|
42 | if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
|
---|
43 | codeA = getCode(a, posA, posA)
|
---|
44 | codeB = getCode(b, posB, posA = i)
|
---|
45 | posB = i
|
---|
46 | }
|
---|
47 |
|
---|
48 | if (codeA != codeB) return (codeA < codeB) ? -1 : 1
|
---|
49 | }
|
---|
50 | return 0
|
---|
51 | }
|
---|
52 |
|
---|
53 | try {
|
---|
54 | module.exports = naturalCompare;
|
---|
55 | } catch (e) {
|
---|
56 | String.naturalCompare = naturalCompare;
|
---|
57 | }
|
---|