Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@swashata
Created December 24, 2019 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashata/49753a2981eae3e6bb16e8fd64e290b6 to your computer and use it in GitHub Desktop.
Save swashata/49753a2981eae3e6bb16e8fd64e290b6 to your computer and use it in GitHub Desktop.
A small dictionary in typescript
export type Dictionary<T> = {
[x: string]: T;
};
export function convertListToDictionary<T extends { id: string }>(
items: T[]
): Dictionary<T> {
const dict: Dictionary<T> = {};
items.forEach(item => {
dict[item.id] = item;
});
return dict;
}
export function convertDictionaryToList<T extends { id: string }>(
dict: Dictionary<T>
): T[] {
return Object.keys(dict).map(key => dict[key]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment