Last active
August 4, 2023 07:00
-
-
Save dmshvetsov/60bb75b867fd09c778a627c42ce3de07 to your computer and use it in GitHub Desktop.
type safe implementation lodash like functions (WIP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type DotPrefix<T extends string> = T extends '' ? '' : `.${T}`; | |
type DotNestedKey<T> = ( | |
T extends object | |
? { | |
[K in Exclude<keyof T, symbol>]: `${K}${DotPrefix< | |
DotNestedKey<T[K]> | |
>}`; | |
}[Exclude<keyof T, symbol>] | |
: '' | |
) extends infer D | |
? Extract<D, string> | |
: never; | |
export funciton getValue(o: T, path: DotNestedKey<T>) | |
export function sortBy<T>( | |
list: T[], | |
key: DotNestedKey<T>, | |
direction: 'asc' | 'desc' = 'asc', | |
): T[] { | |
if (!list.length) { | |
return list; | |
} | |
return list.sort((l, r) => { | |
if (getValue(l, key) > getValue(l, key)) { | |
return direction === 'asc' ? 1 : -1; | |
} else if (getValue(l, key) < getValue(l, key)) { | |
return direction === 'asc' ? -1 : 1; | |
} else { | |
return 0; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment