Skip to content

Instantly share code, notes, and snippets.

@dmshvetsov
Last active August 4, 2023 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmshvetsov/60bb75b867fd09c778a627c42ce3de07 to your computer and use it in GitHub Desktop.
Save dmshvetsov/60bb75b867fd09c778a627c42ce3de07 to your computer and use it in GitHub Desktop.
type safe implementation lodash like functions (WIP)
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