Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

sort-data-by-order.ts

76 lines2.2 KB

1/**
2 * Sorts the items covered by the order rules into the required order, keeping the other items in
3 * place.
4 * @param data - The items to sort.
5 * @param orderRules - Pairs of groups: items whose `key` is in the first group must come before
6 * those in the second.
7 * @param key - The property of each item to compare against the groups.
8 * @returns The sorted items, or `null` if they were already in order.
9 */
10export function sortDataByOrder<T, TKey extends keyof T>(
11 data: Array<T> | ReadonlyArray<T>,
12 orderRules: ReadonlyArray<
13 Readonly<[ReadonlyArray<T[TKey]>, ReadonlyArray<T[TKey]>]>
14 >,
15 key: TKey,
16): Array<T> | null {
17 const getSubsetIndex = (
18 item: T[TKey],
19 subsets: ReadonlyArray<ReadonlyArray<T[TKey]> | Array<T[TKey]>>,
20 ): number | null => {
21 for (let i = 0; i < subsets.length; i++) {
22 if (subsets[i]?.includes(item)) {
23 return i
24 }
25 }
26 return null
27 }
28​
29 const orderSets = orderRules.reduce(
30 (sets, [A, B]) => [...sets, A, B],
31 [] as Array<ReadonlyArray<T[TKey]> | Array<T[TKey]>>,
32 )
33​
34 const inOrderArray = data.filter(
35 (item) => getSubsetIndex(item[key], orderSets) !== null,
36 )
37​
38 let wasResorted = false as boolean
39​
40 // Sort by the relative order defined by the rules
41 const sortedArray = inOrderArray.sort((a, b) => {
42 const aKey = a[key],
43 bKey = b[key]
44 const aSubsetIndex = getSubsetIndex(aKey, orderSets)
45 const bSubsetIndex = getSubsetIndex(bKey, orderSets)
46​
47 // If both items belong to different subsets, sort by their subset order
48 if (
49 aSubsetIndex !== null &&
50 bSubsetIndex !== null &&
51 aSubsetIndex !== bSubsetIndex
52 ) {
53 return aSubsetIndex - bSubsetIndex
54 }
55​
56 // If both items belong to the same subset or neither is in the subset, keep their relative order
57 return 0
58 })
59​
60 const inOrderIterator = sortedArray.values()
61 const result = data.map((item) => {
62 if (getSubsetIndex(item[key], orderSets) !== null) {
63 const sortedItem = inOrderIterator.next().value!
64 if (sortedItem[key] !== item[key]) {
65 wasResorted = true
66 }
67 return sortedItem
68 }
69 return item
70 })
71​
72 if (!wasResorted) {
73 return null
74 }
75 return result