|
1 | | -import { groupBy } from '../../common/util.js'; |
2 | 1 | import type { DataController } from '../controllers/data.js'; |
3 | 2 | import type { ComboRecord, Keys } from '../types.js'; |
4 | 3 |
|
5 | | -export default class GroupDataOperation<T extends object> { |
6 | | - protected orderBy = new Map( |
7 | | - Object.entries({ |
8 | | - asc: 1, |
9 | | - desc: -1, |
10 | | - }) |
11 | | - ); |
| 4 | +const OrderBy = Object.freeze({ asc: 1, desc: -1 }); |
12 | 5 |
|
13 | | - public apply(data: ComboRecord<T>[], controller: DataController<T>) { |
| 6 | +export default class GroupDataOperation<T extends object> { |
| 7 | + public apply( |
| 8 | + data: ComboRecord<T>[], |
| 9 | + controller: DataController<T> |
| 10 | + ): ComboRecord<T>[] { |
14 | 11 | const { |
15 | 12 | groupingOptions: { groupKey, valueKey, displayKey, direction }, |
16 | 13 | } = controller; |
17 | 14 |
|
18 | | - if (!groupKey) return data; |
| 15 | + if (!groupKey) { |
| 16 | + return data; |
| 17 | + } |
19 | 18 |
|
20 | | - const groups = Object.entries( |
21 | | - groupBy(data, (item) => item.value[groupKey] ?? 'Other') |
| 19 | + const grouped = Map.groupBy( |
| 20 | + data, |
| 21 | + (item) => (item.value[groupKey] as string) ?? 'Other' |
22 | 22 | ); |
23 | 23 |
|
| 24 | + const keys = Array.from(grouped.keys()); |
| 25 | + |
24 | 26 | if (direction !== 'none') { |
25 | | - const orderBy = this.orderBy.get(direction); |
26 | | - groups.sort((a, b) => { |
27 | | - return orderBy! * controller.compareCollator.compare(a[0], b[0]); |
28 | | - }); |
| 27 | + const orderBy = OrderBy[direction]; |
| 28 | + keys.sort((a, b) => orderBy * controller.compareCollator.compare(a, b)); |
29 | 29 | } |
30 | 30 |
|
31 | | - return groups.flatMap(([group, items]) => { |
32 | | - items.unshift({ |
33 | | - dataIndex: -1, |
34 | | - header: true, |
35 | | - value: { |
36 | | - [valueKey as Keys<T>]: group, |
37 | | - [displayKey as Keys<T>]: group, |
38 | | - [groupKey as Keys<T>]: group, |
39 | | - } as T, |
40 | | - }); |
41 | | - |
42 | | - return items; |
| 31 | + return keys.flatMap((key) => { |
| 32 | + return [ |
| 33 | + { |
| 34 | + value: { |
| 35 | + [valueKey as Keys<T>]: key, |
| 36 | + [displayKey as Keys<T>]: key, |
| 37 | + [groupKey as Keys<T>]: key, |
| 38 | + } as T, |
| 39 | + header: true, |
| 40 | + dataIndex: -1, |
| 41 | + }, |
| 42 | + ...(grouped.get(key) ?? []), |
| 43 | + ]; |
43 | 44 | }); |
44 | 45 | } |
45 | 46 | } |
0 commit comments