-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.js
73 lines (61 loc) · 1.33 KB
/
iterator.js
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
// iterable object
class Range {
constructor(from, to) {
this.from = from
this.to = to
}
has(x) {
return typeof x === "number" && this.from <= x && x <= this.to
}
toString() {
return `{ x | ${this.from} ≤ x ≤ ${this.to} }`
}
[Symbol.iterator]() {
let next = Math.ceil(this.from)
let last = this.to
return {
next() {
return next <= last ? { value: next++ } : { done: true }
},
// As a convenience, we make the iterator itself iterable.
[Symbol.iterator]() {
return this
},
}
}
}
for (let x of new Range(1, 4)) console.log(x) // Logs numbers 1 to 10
;[...new Range(-2, 2)]
// generators
// infinite generator
function* fibonacciSequence() {
let x = 0,
y = 1
for (;;) {
yield y
;[x, y] = [y, x + y] // Note: destructuring assignment
}
}
function fibonacci(n) {
for (let f of fibonacciSequence()) {
if (n-- <= 0) return f
}
}
const x = fibonacci(20)
x
// async generator
function elapsedTimes(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function* clock(interval, max = Infinity) {
for (let count = 1; count <= max; count++) {
await elapsedTimes(interval)
yield count
}
}
async function test() {
for await (let tick of clock(300, 10)) {
console.log(tick)
}
}
const xxx = test()