-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortas.js
85 lines (63 loc) · 1.7 KB
/
sortas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Shim for CJS Module
if (define === undefined) {
var define = function(fn) {
module.exports = fn()
}
}
// The AMD Module
define(function() {
"use strict"
var sortAs = {
text: function(a, b) {
a = toSortableString(a)
b = toSortableString(b)
if (a === b) return 0
var a, aCode, aNum
var b, bCode, bNum
var codesMatch
var compareNumbers
var startIndex
var i = 0
// if a and b are strings or numbers,
// find and compare the differences only
if (a && b) {
while (1) {
aCode = a.charCodeAt(i)
bCode = b.charCodeAt(i)
codesMatch = aCode === bCode
aNum = aCode <= 57 && aCode >= 48
bNum = bCode <= 57 && bCode >= 48
// if both are numbers, start tracking
if (aNum && bNum) {
if (!compareNumbers) startIndex = i
compareNumbers = true
}
// if neither are numbers, stop tracking
else if (!aNum && !bNum) {
startIndex = i
compareNumbers = false
}
// if not the same, break
if (!codesMatch) break
i++
}
a = a.substring(startIndex) || null
b = b.substring(startIndex) || null
}
// compare strings
if (a === b) return 0
if (!a) return -1
if (!b) return 1
if (!compareNumbers) return a < b ? -1 : 1
// compare numbers
aNum = parseInt(a)
bNum = parseInt(b)
return aNum < bNum ? -1 : 1
}
}
// Private Methods
function toSortableString(x) {
return (x || x === 0) && typeof x !== 'object' ? x.toString().toLowerCase() : null
}
return sortAs
})