-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort.ts
61 lines (55 loc) · 2.07 KB
/
sort.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
interface SortOptions<T> {
getter?: (item: T) => number
desc?: boolean
}
/**
* Sorts an array of objects or numbers based on a specified getter function.
*
* @template T - The type of the array elements.
* @param {readonly T[]} arr - The array to be sorted.
* @param {SortOptions<T>} [options] - The sorting options.
* @param {Function} [options.getter] - The getter function to extract the value to be used for sorting.
* @param {boolean} [options.desc] - Specifies whether to sort in descending order.
* @returns {T[]} - The sorted array.
* @example
* ```ts
* sort([3, 1, 2]) // [1, 2, 3]
* sort([3, 1, 2], { desc: true }) // [3, 2, 1]
* sort([{ value: 3 }, { value: 1 }, { value: 2 }], { getter: item => item.value }) // [{ value: 1 }, { value: 2 }, { value: 3 }]
* ```
*/
export function sort<T extends number>(arr: readonly T[], options?: SortOptions<T>): T[]
export function sort<T extends object>(
arr: readonly T[],
options: SortOptions<T>
): T[]
export function sort<T extends object | number>(
arr: readonly T[],
options: SortOptions<T> = {},
): T[] {
const { getter, desc = false } = options
const getter_ = (item: T) => getter ? getter(item) : item as number
const asc = (a: T, b: T) => getter_(a) - getter_(b)
const dsc = (a: T, b: T) => getter_(b) - getter_(a)
return arr.slice().sort(desc ? dsc : asc)
}
interface AlphabeticalOptions<T> {
getter?: (item: T) => string
desc?: boolean
locales?: Intl.LocalesArgument
}
export function alphabetical<T extends string>(arr: readonly T[], options?: AlphabeticalOptions<T>): T[]
export function alphabetical<T extends object>(
arr: readonly T[],
options: AlphabeticalOptions<T>
): T[]
export function alphabetical<T extends object | string>(
arr: readonly T[],
options: AlphabeticalOptions<T> = {},
): T[] {
const { getter, desc = false } = options
const getter_ = (item: T) => getter ? getter(item) : item as string
const asc = (a: T, b: T) => getter_(a).localeCompare(getter_(b))
const dsc = (a: T, b: T) => getter_(b).localeCompare(getter_(a))
return arr.slice().sort(desc ? dsc : asc)
}