Created
December 24, 2019 01:31
-
-
Save swashata/49753a2981eae3e6bb16e8fd64e290b6 to your computer and use it in GitHub Desktop.
A small dictionary in typescript
This file contains hidden or 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 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