Add imapfilter function

This commit is contained in:
Michaël Lemaire 2021-08-26 23:36:25 +02:00
parent db54d4f444
commit 43d5678697
4 changed files with 34 additions and 1 deletions

View file

@ -64,6 +64,7 @@ iloop(i1); // 1 2 3 1 2 3 ...
iskip(i3, 2); // -2 -3 -4 -5 -6 ...
imap(i1, (x) => x * 2); // 2 4 6
ifilter(i3, (x) => x % 4 == 0); // 0 -4 -8 -12 ...
imapfilter(i1, (x) => x != 4 ? x * 2 : null); // 2 6
ipartition(i3, (x) => x % 4 == 0); // [0 -4 -8 ..., -1 -2 -3 -5 ...]
iunique(iarray([1, 4, 2, 4, 3, 1, 5])); // 1 4 2 3 5

View file

@ -30,6 +30,7 @@ iloop(i1); // 1 2 3 1 2 3 ...
iskip(i3, 2); // -2 -3 -4 -5 -6 ...
imap(i1, (x) => x * 2); // 2 4 6
ifilter(i3, (x) => x % 4 == 0); // 0 -4 -8 -12 ...
imapfilter(i1, (x) => x != 4 ? x * 2 : null); // 2 6
ipartition(i3, (x) => x % 4 == 0); // [0 -4 -8 ..., -1 -2 -3 -5 ...]
iunique(iarray([1, 4, 2, 4, 3, 1, 5])); // 1 4 2 3 5

View file

@ -17,6 +17,7 @@ import {
ilength,
iloop,
imap,
imapfilter,
imaterialize,
imax,
imin,
@ -241,10 +242,20 @@ describe("Iterators", () => {
});
it("filters an iterator with a predicate", () => {
checkit(imap(IEMPTY, (i) => i % 3 == 0), []);
checkit(ifilter(IEMPTY, (i) => i % 3 == 0), []);
checkit(ifilter(irange(12), (i) => i % 3 == 0), [0, 3, 6, 9]);
});
it("maps and filters in a single pass", () => {
checkit(imapfilter(IEMPTY, (i) => i % 2 == 0 ? -i : null), []);
checkit(imapfilter(irange(8), (i) => i % 2 == 0 ? -i : null), [
-0,
-2,
-4,
-6,
]);
});
it("filters an iterator with a type guard", () => {
let result: Iterable<number> = ifiltertype(
<(number | string)[]> [1, "a", 2, "b"],

20
mod.ts
View file

@ -338,6 +338,26 @@ export function ifilter<T>(
};
}
/**
* Apply map, and filter invalid results in the same pass.
*/
export function imapfilter<T1, T2, E>(
iterable: Iterable<T1>,
mapfunc: (_: T1) => Exclude<T2, E> | typeof exclusion,
exclusion: E = null as unknown as E,
): Iterable<T2> {
return {
[Symbol.iterator]: function* () {
for (let value of iterable) {
const mapped = mapfunc(value);
if (mapped !== exclusion) {
yield mapped as T2;
}
}
},
};
}
/**
* Type filter, to return a list of instances of a given type
*/