blob: 2ba872a6f5ef50881e6c4ac7a7963a806ca65d69 (
plain) (
blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import {IterableElement, Promisable} from 'type-fest';
export function pSomeFunction<
List extends Iterable<unknown>,
Element extends IterableElement<List>,
>(
iterable: List,
predicate: (value: Element) => Promisable<boolean>,
): Promisable<boolean> {
const promises: Array<PromiseLike<boolean>> = [];
// Prioritize sync functions and early returns
for (const item of iterable) {
const result = predicate(item as Element);
if (typeof result === 'boolean') {
if (result) {
// Early sync return on the first truthy value
return true;
}
} else {
promises.push(result);
}
}
if (promises.length === 0) {
// Matches `[].some(Boolean)`
return false;
}
return pSome(promises);
}
export async function pSome(iterable: Iterable<PromiseLike<unknown>>): Promise<boolean> {
return new Promise(resolve => {
for (const promise of iterable) {
(async () => {
if (await promise) {
resolve(true);
}
})();
}
void Promise.allSettled(iterable).then(() => {
resolve(false);
});
});
}
export function pEveryFunction<
List extends Iterable<unknown>,
Element extends IterableElement<List>,
>(
iterable: List,
predicate: (value: Element) => Promisable<boolean>,
): Promisable<boolean> {
const promises: Array<PromiseLike<boolean>> = [];
// Prioritize sync functions and early returns
for (const item of iterable) {
const result = predicate(item as Element);
if (typeof result === 'boolean') {
if (!result) {
// Early sync return on the first falsy value
return false;
}
} else {
promises.push(result);
}
}
if (promises.length === 0) {
// Matches `[].every(Boolean)`
return true;
}
return pEvery(promises);
}
export async function pEvery(iterable: Iterable<PromiseLike<unknown>>): Promise<boolean> {
const results = await Promise.all(iterable);
return results.every(Boolean);
}
|