-
Notifications
You must be signed in to change notification settings - Fork 0
/
Order.ts
executable file
·69 lines (63 loc) · 1.65 KB
/
Order.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
/**
* Provides ordering to the result set..
*/
import {Props} from "wasabi-common";
export interface OrderItem<E> {
key: string;
sort: OrderCallback<E>;
}
export interface OrderCallback<E> {
(dataList: E[]): E[];
}
class Order {
/**
*
* Sorts ascending the data by given key.
* @param {string} key
* @return {Function}
*/
public static asc<E>(key: string): OrderItem<E> {
return {
key,
sort: Order.sort(key, false)
};
}
/**
* Sorts descending given data by given key.
* @param {string} key
* @return {Function}
*/
public static desc<E>(key: string): OrderItem<E> {
return {
key,
sort: Order.sort(key, true)
};
}
/**
*
* Sorts given data by given key and sorted type.
* @param {string} key
* @param {boolean} isDesc
* @return {Function}
* @private
*/
private static sort<E>(key: string, isDesc: boolean): OrderCallback<E> {
const less: number = isDesc ? 1 : -1;
const greater: number = isDesc ? -1 : 1;
return (dataList: E[]): E[] => {
dataList.sort((source: Props<any>, destination: Props<any>): number => {
const sourceValue = source[key];
const destinationValue = destination[key];
if (sourceValue === destinationValue) {
return 0;
}
if (sourceValue < destinationValue) {
return less;
}
return greater;
});
return dataList;
};
}
}
export default Order;