This repository was archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.ts
54 lines (53 loc) · 1.57 KB
/
filter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type {
IsomorphicIterable,
Predicate,
Single,
Unary,
} from "@vangware/types";
import { handleIsomorphicIterable } from "./handleIsomorphicIterable.js";
import type { GeneratorOutput } from "./types/GeneratorOutput.js";
/**
* Filters items in an iterable or asynchronous iterable against a predicate and
* returns items that evaluated to `true`.
*
* @category Generators
* @example
* ```
* const filterEven = filter((number: number) => number % 2 === 0);
*
* iterableToArray(filterEven([1, 2, 3, 4])); // [2, 4]
* iterableToArray(filterEven([1, 3, 5, 7])); // []
* ```
* @param predicate Predicate function to evaluate each item.
* @returns Curried function with `predicate` set in context.
*/
export const filter = <Item, Filtered extends Item = never>(
predicate: Single<Filtered> extends Single<never>
? Unary<Item, boolean>
: Predicate<Item, Filtered>,
) =>
handleIsomorphicIterable<Item, Filtered>(
iterable =>
function* () {
// eslint-disable-next-line functional/no-loop-statements
for (const item of iterable) {
// eslint-disable-next-line functional/no-conditional-statements
if (predicate(item)) {
yield item as Filtered;
}
}
},
)(
iterable =>
async function* () {
// eslint-disable-next-line functional/no-loop-statements
for await (const item of iterable) {
// eslint-disable-next-line functional/no-conditional-statements
if (predicate(item)) {
yield item as Filtered;
}
}
},
) as <Iterable extends IsomorphicIterable<Item>>(
iterable: Iterable,
) => GeneratorOutput<Iterable>;