import { useWhoAmI } from "../context/whoami/WhoAmI"; export type ValueMapperFn = (item: T) => string | undefined; export default function useLocaleSort() { const { whoAmI } = useWhoAmI(); return function localeSort(items: T[], mapperFn: ValueMapperFn): 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 = { [K in keyof T]: T[K] extends V ? K : never; }[keyof T]; export const mapByKey = < T extends { [_ in K]?: string }, K extends KeysMatching, >( key: K, ) => (item: T) => item[key];