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 pathevery.ts
51 lines (48 loc) · 1.48 KB
/
every.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
import type {
IsomorphicIterable,
Predicate,
Single,
Unary,
} from "@vangware/types";
import { whenIsIterable } from "@vangware/utils";
import type { ReducerOutput } from "./types/ReducerOutput.js";
/**
* Evaluates items in an iterable or asynchronous iterable against a predicate
* and returns `true` if all items evaluates to `true`.
*
* @category Reducers
* @example
* ```typescript
* const everyEven = every((number: number) => number % 2 === 0);
* everyEven([2, 4, 6, 8]); // true
* everyEven([1, 2, 3, 4]); // false
* ```
* @param predicate Predicate function to evaluate each item.
* @returns Curried function with `predicate` set in context.
*/
export const every = <Item, Predicated extends Item = never>(
predicate: Single<Predicated> extends Single<never>
? Unary<Item, boolean>
: Predicate<Item, Predicated>,
) =>
whenIsIterable(iterable => {
// eslint-disable-next-line functional/no-loop-statements
for (const item of iterable) {
// eslint-disable-next-line functional/no-conditional-statements
if (!predicate(item as Item)) {
return false;
}
}
return true;
})(async (iterable: AsyncIterable<Item>) => {
// 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)) {
return false;
}
}
return true;
}) as <Iterable extends IsomorphicIterable<Item>>(
iterable: Iterable,
) => ReducerOutput<Iterable, boolean>;