Skip to content

Instantly share code, notes, and snippets.

@DPros
Last active April 3, 2020 09:39
Show Gist options
  • Save DPros/d0a7d28dcaa4a161b753354f14526421 to your computer and use it in GitHub Desktop.
Save DPros/d0a7d28dcaa4a161b753354f14526421 to your computer and use it in GitHub Desktop.
generic reduce wrappers
export function toObject<T>(entries: [string, T][]): Record<string, T>;
export function toObject<T>(entries: [keyof T, T[keyof T]][]) {
return entries.reduce((object, [key, value]) => {
object[key] = value;
return object;
}, {} as T);
}
export function toDictionary<T, K extends keyof T>(objects: T[], keySelector: K | ((object: T) => string)) {
return objects.reduce((dictionary, object) => {
dictionary[typeof keySelector === "string" ? object[keySelector] as unknown as string : (keySelector as (o: T) => string)(object)] = object;
return dictionary;
}, {} as Record<string, T>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment