1export function sortObject<T extends Record<string, any> = Record<string, any>>(
2  obj: T,
3  compareFn?: (a: string, b: string) => number
4): T {
5  return Object.keys(obj)
6    .sort(compareFn)
7    .reduce(
8      (acc, key) => ({
9        ...acc,
10        [key]: obj[key],
11      }),
12      {}
13    ) as T;
14}
15
16export function sortObjWithOrder<T extends Record<string, any> = Record<string, any>>(
17  obj: T,
18  order: string[]
19): T {
20  const sorted = sortWithOrder(Object.keys(obj), order);
21
22  return sorted.reduce(
23    (acc, key) => ({
24      ...acc,
25      [key]: obj[key],
26    }),
27    {}
28  ) as T;
29}
30
31export function sortWithOrder(obj: string[], order: string[]): string[] {
32  const groupOrder = [...new Set(order.concat(obj))];
33  const sorted: string[] = [];
34
35  while (groupOrder.length) {
36    const key = groupOrder.shift()!;
37    const index = obj.indexOf(key);
38    if (index > -1) {
39      const [item] = obj.splice(index, 1);
40      sorted.push(item);
41    }
42  }
43
44  return sorted;
45}
46
47export const reverseSortString = (a: string, b: string) => {
48  if (a < b) return 1;
49  if (a > b) return -1;
50  return 0;
51};
52