-
Notifications
You must be signed in to change notification settings - Fork 2
/
repeat.ts
47 lines (34 loc) · 925 Bytes
/
repeat.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
function repeat(asyncIterable) {
if (typeof asyncIterable !== "object" && typeof asyncIterable !== "function") {
throw new Error("element is not async iterable");
}
if (typeof asyncIterable === "function" && asyncIterable[Symbol.asyncIterator] === undefined) {
asyncIterable[Symbol.asyncIterator] = function() {
return asyncIterable();
};
}
let currentAsyncIterator = asyncIterable[Symbol.asyncIterator]();
let isWork = true;
let lastEvent = null;
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
if (!isWork) {
isWork = true;
currentAsyncIterator = asyncIterable[Symbol.asyncIterator]();
}
const { value, done } = await currentAsyncIterator.next();
if (value !== undefined) {
lastEvent = value;
}
if (done) {
isWork = false;
return { value: lastEvent, done: false };
}
return { value, done };
}
};
};
export { repeat };