-
Notifications
You must be signed in to change notification settings - Fork 0
/
infinite.ts
225 lines (215 loc) · 5.06 KB
/
infinite.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/**
* Makes an infinite async iterable of evenly spaced values starting with
* the `start` number.
*
* ``` typescript
* import { count } from "./infinite.ts";
* const iterable = count(5);
* for await (const value of iterable) {
* console.log(value);
* }
* ```
*
* The above example will print the following and keep going forever:
*
* ~~~
* 5
* 6
* 7
* 8
* 9
* (...)
* ~~~
*
* You could adjust the interval by passing a second argument to `count()`:
*
* ``` typescript
* import { count } from "./infinite.ts";
* const iterable = count(0, 3);
* for await (const value of iterable) {
* console.log(value);
* }
* ```
*
* The above example will print the following and keep going forever:
*
* ~~~
* 0
* 3
* 6
* 9
* 12
* (...)
* ~~~
*
* As it's infinite, it's usually used with `break` to stop the iteration:
*
* ``` typescript
* import { count } from "./infinite.ts";
* for await (const value of count(0)) {
* if (value > 4) break;
* console.log(value);
* }
* ```
*
* Or with other async generators like `takeWhile()`:
*
* ``` typescript
* import { count } from "./infinite.ts";
* import { takeWhile } from "./take.ts";
* for await (const value of takeWhile(count(0), v => v <= 4)) {
* console.log(value);
* }
* ```
*
* The both examples above will print the following 4 lines:
*
* ~~~
* 0
* 1
* 2
* 3
* ~~~
*
* @param start The first value in the sequence. Defaults to 0.
* @param step The difference between each value in the sequence.
* Defaults to 1.
* @returns An async iterable of evenly spaced values.
*/
export function count(start = 0, step = 1): AsyncIterableIterator<number> {
return new Counter(start, step);
}
class Counter implements AsyncIterableIterator<number> {
#i: number;
constructor(readonly start: number, readonly step: number) {
this.#i = start;
}
[Symbol.asyncIterator]() {
return this;
}
next(): Promise<IteratorResult<number>> {
return new Promise((resolve, _) => {
const result = { done: false, value: this.#i };
this.#i += this.step;
resolve(result);
});
}
}
/**
* Makes an async iterator that yields elements from the `source` and saving
* a copy of each. When the `source` is exhausted, yields saved copies
* indefinitely.
*
* Note that it may require significant memory to save the copies
* depending on the length of the `source`.
*
* ``` typescript
* import { cycle } from "./infinite.ts";
*
* async function* gen() { yield 3; yield 6; yield 9; }
* const iterable = cycle(gen());
* for await (const value of iterable) console.log(value);
* ```
*
* The above example will print the following and keep going forever:
*
* ~~~
* 3
* 6
* 9
* 3
* 6
* 9
* (...)
* ~~~
*
* @template T The type of the elements in the `source` and the returned async
* iterable.
* @param source An async iterable to repeat.
* @returns An async iterable that repeats the `source` indefinitely.
*/
export async function* cycle<T>(
source: Iterable<T> | AsyncIterable<T>,
): AsyncIterableIterator<T> {
const cache = [];
for await (const value of source) {
yield value;
cache.push(value);
}
while (cache.length > 0) {
for await (const value of cache) {
yield value;
}
}
}
/**
* Makes an async iterator that yields the same value over and over again.
* It will repeat indefinitely unless `times` is specified.
*
* ``` typescript
* import { repeat } from "./infinite.ts";
*
* const iterable = repeat("v");
* for await (const value of iterable) console.log(value);
* ```
*
* The above example will print the following and keep going forever:
*
* ~~~
* v
* v
* v
* (...)
* ~~~
*
* However, if you specify the second parameter `times` it will repeat that many
* times:
*
* ``` typescript
* import { repeat } from "./infinite.ts";
*
* const iterable = repeat("V", 3);
* for await (const value of iterable) console.log(value);
* ```
*
* The above example will print the following 3 lines:
*
* ~~~
* V
* V
* V
* ~~~
*
* @template T The type of the `value` and the elements in the returned async
* iterable.
* @param value The value to repeat.
* @param times The number of times to repeat. Defaults to `Infinity`.
* @returns An async iterable that repeats the `value` indefinitely or
* `times` times.
* @throws {RangeError} when `times` is not a non-negative integer.
*/
export function repeat<T>(
value: T,
times = Infinity,
): AsyncIterableIterator<T> {
if (times === Infinity) return new InfiniteRepeater(value);
if (!Number.isInteger(times) || times < 0) {
throw new RangeError("times must be a non-negative integer");
}
return repeatDefinitely(value, times);
}
async function* repeatDefinitely<T>(
value: T,
times: number,
): AsyncIterableIterator<T> {
for (let i = 0; i < times; i++) yield value;
}
class InfiniteRepeater<T> implements AsyncIterableIterator<T> {
constructor(readonly value: T) {}
[Symbol.asyncIterator]() {
return this;
}
next(): Promise<IteratorResult<T>> {
return Promise.resolve({ done: false, value: this.value });
}
}