2022-05-09 10:44:07 +00:00
|
|
|
import { useWhoAmI } from "../context/whoami/WhoAmI";
|
|
|
|
|
|
|
|
export type ValueMapperFn<T> = (item: T) => string | undefined;
|
|
|
|
|
|
|
|
export default function useLocaleSort() {
|
|
|
|
const { whoAmI } = useWhoAmI();
|
|
|
|
|
|
|
|
return function localeSort<T>(items: T[], mapperFn: ValueMapperFn<T>): T[] {
|
|
|
|
const locale = whoAmI.getLocale();
|
|
|
|
|
|
|
|
return [...items].sort((a, b) => {
|
|
|
|
const valA = mapperFn(a);
|
|
|
|
const valB = mapperFn(b);
|
|
|
|
|
|
|
|
if (valA === undefined || valB === undefined) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return valA.localeCompare(valB, locale);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: This might be built into TypeScript into future.
|
|
|
|
// See: https://github.com/microsoft/TypeScript/issues/48992
|
|
|
|
type KeysMatching<T, V> = {
|
|
|
|
[K in keyof T]: T[K] extends V ? K : never;
|
|
|
|
}[keyof T];
|
|
|
|
|
|
|
|
export const mapByKey =
|
|
|
|
<
|
|
|
|
T extends { [_ in K]?: string },
|
2023-07-11 14:03:21 +00:00
|
|
|
K extends KeysMatching<T, string | undefined>,
|
2022-05-09 10:44:07 +00:00
|
|
|
>(
|
2023-07-11 14:03:21 +00:00
|
|
|
key: K,
|
2022-05-09 10:44:07 +00:00
|
|
|
) =>
|
|
|
|
(item: T) =>
|
|
|
|
item[key];
|