-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathorder-by.ts
75 lines (61 loc) · 1.95 KB
/
order-by.ts
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
import {PipeTransform, Pipe} from '@angular/core';
import GeneralHelper from '../helpers/helpers';
@Pipe({name: 'orderBy'})
export class OrderByPipe implements PipeTransform {
transform(arr: any, config?: any): any[] {
if (!Array.isArray(arr)) {
return arr;
}
const out = [...arr];
// sort by multiple properties
if (Array.isArray(config)) {
return out.sort((a, b) => {
for (let i=0, l=config.length; i<l; ++i) {
const [prop, asc] = OrderByPipe.extractFromConfig(config[i]);
const pos = OrderByPipe.orderCompare(prop, asc, a, b);
if (pos !== 0) {
return pos;
}
}
return 0;
});
}
// sort by a single property value
if (GeneralHelper.isString(config)) {
const [prop, asc, sign] = OrderByPipe.extractFromConfig(config);
if (config.length === 1) {
switch (sign) {
case '+': return out.sort();
case '-': return out.sort().reverse();
}
}
return out.sort(OrderByPipe.orderCompare.bind(this, prop, asc));
}
// default sort by value
return out.sort((a, b) => {
return GeneralHelper.isString(a) && GeneralHelper.isString(b)
? a.toLowerCase().localeCompare(b.toLowerCase())
: a - b;
});
}
static orderCompare(prop, asc, a, b) {
const first = GeneralHelper.extractDeepPropertyByMapKey(a, prop),
second = GeneralHelper.extractDeepPropertyByMapKey(b, prop);
if (first === second) {
return 0;
}
if (GeneralHelper.isString(first) && GeneralHelper.isString(second)) {
const pos = first.toLowerCase().localeCompare(second.toLowerCase());
return asc ? pos : -pos;
}
return asc
? first - second
: second - first;
}
static extractFromConfig(config) {
const sign = config.substr(0, 1);
const prop = config.replace(/^[-+]/, '');
const asc = sign !== '-';
return [prop, asc, sign];
}
}