1 | module.exports = sort
|
2 |
|
3 | function sort (comparator) {
|
4 | if (typeof comparator != 'function') {
|
5 | var sortKeys = Array.isArray(comparator)
|
6 | ? comparator
|
7 | : Object.keys(this.columns)
|
8 | comparator = KeysComparator(sortKeys)
|
9 | }
|
10 | this.rows.sort(comparator)
|
11 | return this
|
12 | }
|
13 |
|
14 | function KeysComparator (keys) {
|
15 | var comparators = keys.map(function (key) {
|
16 | var sortFn = 'asc'
|
17 |
|
18 | var m = /(.*)\|\s*(asc|des)\s*$/.exec(key)
|
19 | if (m) {
|
20 | key = m[1]
|
21 | sortFn = m[2]
|
22 | }
|
23 |
|
24 | return function (a, b) {
|
25 | var ret = compare(a[key], b[key])
|
26 | return sortFn == 'asc' ? ret : -1 * ret
|
27 | }
|
28 | })
|
29 |
|
30 | return function (a, b) {
|
31 | for (var i = 0; i < comparators.length; i++) {
|
32 | var res = comparators[i](a, b)
|
33 | if (res != 0) return res
|
34 | }
|
35 | return 0
|
36 | }
|
37 | }
|
38 |
|
39 | function compare (a, b) {
|
40 | if (a === b) return 0
|
41 | if (a === undefined) return 1
|
42 | if (b === undefined) return -1
|
43 | if (a === null) return 1
|
44 | if (b === null) return -1
|
45 | if (a > b) return 1
|
46 | if (a < b) return -1
|
47 | return compare(String(a), String(b))
|
48 | } |
\ | No newline at end of file |