Skip to content

Instantly share code, notes, and snippets.

@ProdigySim
Created August 16, 2018 17:08
Show Gist options
  • Select an option

  • Save ProdigySim/1cf53ed22b4717e55fc8b1d170bd49c2 to your computer and use it in GitHub Desktop.

Select an option

Save ProdigySim/1cf53ed22b4717e55fc8b1d170bd49c2 to your computer and use it in GitHub Desktop.
Doing some neat typescript stuff.
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