You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
1.0 KiB
TypeScript

2 years ago
export function validateObjectKeys<K extends string>(obj: any, keys: K[]): boolean {
const keySet = new Set(keys)
// @ts-ignore
return Object.keys(obj).every(key => keySet.has(key))
}
function compareStringKeys(a: string, b: string): number {
return a === b ? 0 : a < b ? -1 : 1
}
function compareNumberKeys(a: number, b: number): number {
return a === b ? 0 : a < b ? -1 : 1
}
type KeyFn<T, K> = (item: T) => K
export function sortByStringKey<T>(items: T[], keyFn: KeyFn<T, string>, ascending: boolean = true) {
return sortByKey(compareStringKeys, items, keyFn, ascending)
}
export function sortByNumericKey<T>(items: T[], keyFn: KeyFn<T, number>, ascending: boolean = true) {
return sortByKey(compareNumberKeys, items, keyFn, ascending)
}
function sortByKey<T, K>(compareFn: (a: K, b: K) => number, items: T[], keyFn: (item: T) => K, ascending: boolean) {
const sortedList = [...items]
const order = ascending ? 1 : -1
sortedList.sort((a, b) => order * compareFn(keyFn(a), keyFn(b)))
return sortedList
}