Created
August 16, 2018 17:08
-
-
Save ProdigySim/1cf53ed22b4717e55fc8b1d170bd49c2 to your computer and use it in GitHub Desktop.
Doing some neat typescript stuff.
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
| type FilterFn<T> = (item: T) => boolean; | |
| type FilterMap<T> = Record<string, FilterFn<T>>; | |
| function filterMap<T, U extends FilterMap<T>>(items: T[], filterMap: U) { | |
| const filters = new Map<string, FilterFn<T>>(); | |
| Object.keys(filterMap).forEach((key) => filters.set(key, filterMap[key])); | |
| const itemMap: Partial<Record<keyof U, T>> = {}; | |
| for (const item of items) { | |
| const matchedFilter = Array.from(filters).find(([key, filterFn]) => { | |
| return filterFn(item); | |
| }) | |
| if (matchedFilter) { | |
| const key = matchedFilter[0]; | |
| itemMap[key] = item; | |
| filters.delete(key); | |
| } | |
| } | |
| return itemMap; | |
| } | |
| const items = [{ type: 'cool' }, { type: 'hot' }]; | |
| const mapped = filterMap(items, { | |
| cool: (item) => item.type === 'cool', | |
| hot: (item) => item.type === 'hot'; | |
| }); | |
| // mapped.hot, mapped.cool are type checked & typeahead completed by typescript | |
| console.log(mapped.hot); | |
| console.log(mapped.cool); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment