-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.ts
More file actions
60 lines (53 loc) · 1.84 KB
/
mod.ts
File metadata and controls
60 lines (53 loc) · 1.84 KB
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
export class AsyncIterator<T> implements AsyncIterable<T> {
constructor(private iterable: AsyncIterable<T>) {}
[Symbol.asyncIterator]() {
return this.iterable[Symbol.asyncIterator]()
}
map<U>(transformer: (value: T) => U | Promise<U>): AsyncIterator<U> {
const original = this.iterable
return new AsyncIterator((async function* () {
for await (const item of original) {
yield await transformer(item)
}
})())
}
take(limit: number): AsyncIterator<T> {
const original = this.iterable
return new AsyncIterator((async function* () {
let count = 0
if (limit <= 0) return
for await (const item of original) {
yield item
if (++count >= limit) break
}
})())
}
filter(predicate: (value: T) => boolean | Promise<boolean>): AsyncIterator<T> {
const original = this.iterable
return new AsyncIterator((async function* () {
for await (const item of original) {
if (await predicate(item)) yield item
}
})())
}
async forEach(action: (value: T) => void | Promise<void>): Promise<void> {
for await (const item of this.iterable) {
await action(item)
}
}
async toArray(): Promise<T[]> {
const result: T[] = []
for await (const item of this.iterable) {
result.push(item)
}
return result
}
static from<U>(iterable: AsyncIterable<U> | Iterable<U>): AsyncIterator<U> {
if (Symbol.asyncIterator in iterable) {
return new AsyncIterator(iterable as AsyncIterable<U>)
}
return new AsyncIterator((async function* () {
for (const item of iterable as Iterable<U>) yield item
})())
}
}