Skip to content

Commit

Permalink
feat: better typing on filterMap for use with predicates
Browse files Browse the repository at this point in the history
  • Loading branch information
wschurman committed Jan 8, 2021
1 parent 8354741 commit 5e0f697
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
14 changes: 14 additions & 0 deletions packages/entity/src/utils/collections/__tests__/maps-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,18 @@ describe(filterMap, () => {
expect(filteredMap.get('a')).toBeUndefined();
expect(filteredMap.get('b')).toBe(true);
});

it('can use predicates', () => {
function truthy<TValue>(value: TValue | null | undefined): value is TValue {
return !!value;
}

const map = new Map<string, string | null>([
['a', 'yes'],
['b', null],
]);

const filteredMap: Map<string, string> = filterMap(map, truthy);
expect(filteredMap.size).toBe(1);
});
});
14 changes: 11 additions & 3 deletions packages/entity/src/utils/collections/maps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,23 @@ export const reduceMapAsync = async <K, V, A>(
return newAccumulator;
};

export const filterMap = <K, V>(
export function filterMap<K, V, S extends V>(
map: ReadonlyMap<K, V>,
predicate: (value: V, key: K) => value is S
): Map<K, S>;
export function filterMap<K, V>(
map: ReadonlyMap<K, V>,
predicate: (value: V, key: K) => boolean
): Map<K, V> => {
): Map<K, V>;
export function filterMap<K, V>(
map: ReadonlyMap<K, V>,
predicate: (value: V, key: K) => unknown
): Map<K, V> {
const resultingMap = new Map();
map.forEach((v, k) => {
if (predicate(v, k)) {
resultingMap.set(k, v);
}
});
return resultingMap;
};
}

0 comments on commit 5e0f697

Please sign in to comment.