Last active
April 3, 2020 09:39
-
-
Save DPros/d0a7d28dcaa4a161b753354f14526421 to your computer and use it in GitHub Desktop.
generic reduce wrappers
This file contains 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
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