Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created July 17, 2019 20:49
Show Gist options
  • Save sebinsua/c64edc785d4cccfb196bec42927732e0 to your computer and use it in GitHub Desktop.
Save sebinsua/c64edc785d4cccfb196bec42927732e0 to your computer and use it in GitHub Desktop.
type GetValueFn<TIdentity, TValue> = (id: TIdentity) => Promise<TValue>;
type KeyValueObject<TValue> = { [key: string]: TValue };
const getObject = <TIdentity, TValue>(
getValue: GetValueFn<TIdentity, TValue>
) => async (itemIds: Array<TIdentity>): Promise<KeyValueObject<TValue>> => {
return Object.fromEntries(
await Promise.all(
itemIds.map(async itemId => [itemId, await getValue(itemId)])
)
);
};
type Movie = Readonly<{ id: number; title: string }>;
const getMovie = async (id: number): Promise<Movie> => {
switch (id) {
case 1:
return { id, title: "Avengers: Endgame" };
case 2:
return { id, title: "Toy Story 4" };
case 3:
return { id, title: "The Lion King" };
case 4:
return { id, title: "Aladdin" };
case 5:
return { id, title: "Captain Marvel" };
}
throw new Error("No movie could be found with this id.");
};
(async (): Promise<void> => {
const getMovies = getObject(getMovie);
const movies = await getMovies([1, 2, 3]);
// {
// 1: { id: 1, title: "Avengers: Endgame" },
// 2: { id: 2, title: "Toy Story 4" },
// 3: { id: 3, title: "The Lion King" },
// }
console.log(movies);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment