-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path7-async-array.js
More file actions
62 lines (53 loc) · 1.21 KB
/
7-async-array.js
File metadata and controls
62 lines (53 loc) · 1.21 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
61
62
'use strict';
const INTERVAL = 100;
class AsyncArray extends Array {
interval(ms) {
this._interval = ms;
return this;
}
[Symbol.asyncIterator]() {
let time = Date.now();
let i = 0;
const interval = this._interval || INTERVAL;
return {
next: () => {
const now = Date.now();
const diff = now - time;
if (diff > interval) {
time = now;
return new Promise(resolve => {
setTimeout(() => {
resolve({
value: this[i],
done: i++ === this.length
});
}, 0);
});
}
return Promise.resolve({
value: this[i],
done: i++ === this.length
});
}
};
}
}
// Usage
let k = 0;
const timer = setInterval(() => {
console.log('next ', k++);
}, 10);
(async () => {
const numbers = new AsyncArray(10000)
.interval(100)
.fill(1);
const begin = process.hrtime.bigint();
let i = 0;
for await (const number of numbers) {
console.log(number, i++);
}
clearInterval(timer);
const diff = (process.hrtime.bigint() - begin) / 1000000n;
console.log('Time(ms):', diff.toString());
console.dir({ k });
})();