-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
81 lines (69 loc) · 1.77 KB
/
index.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
var log = console.log.bind(console);
var prototypeOf = function(object){
return Object.prototype.toString.call(object).split(' ')[1].slice(0, 6)
}
var normalizeWww = function(domainName){
return domainName.split('www.').reverse()[0]
}
var reverseDomainName = function(domainName){
return domainName.split('.').reverse().join('.')
}
// These are inside a var as other sorts use them!
var sorts = {
byLength: function (a, b) {
return a.length - b.length
},
byNumber: function(a,b) {
return a - b;
},
alphabetical: function(a,b){
if ( prototypeOf(a) !== 'String' || prototypeOf(b) !== 'String' ) {
log('Warning:', a, 'is not a string')
return false;
}
return a.localeCompare(b);
},
domainName: function(a,b){
if ( prototypeOf(a) !== 'String' || prototypeOf(b) !== 'String' ) {
log('Warning:', a, 'is not a string')
return false;
}
var aWasWww = a.startsWith('www.');
var bWasWww = b.startsWith('www.');
a = normalizeWww(a);
b = normalizeWww(b);
// Eg, we are comparing www.foo.com to foo.com
if ( a === b && aWasWww !== bWasWww) {
return aWasWww ? 1 : -1;
}
// Let's reverse the domain names
a = reverseDomainName(a)
b = reverseDomainName(b)
return a.localeCompare(b);
}
}
var alphabetical = function(a,b){
if ( prototypeOf(a) !== 'String' ) {
log('Warning:', a, 'is not a string')
return false;
}
return a.localeCompare(b);
}
var byKey = function(property, sortName){
return function(a,b) {
var sortFunction = sorts[sortName]
if ( ! sortFunction ) {
sortFunction = sorts.alphabetical
}
return sortFunction(a[property], b[property])
}
}
module.exports = {
byLength: sorts.byLength,
byNumber: sorts.byNumber,
byKey,
domainName: sorts.domainName,
alphabetical: sorts.alphabetical,
// Aliases
numeric: sorts.byNumber
}