-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.js
More file actions
75 lines (63 loc) · 1.36 KB
/
iterator.js
File metadata and controls
75 lines (63 loc) · 1.36 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
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Iterator
*
* Iterator is a behavioral design pattern that provides a way to
* access elements of a collection sequentially without exposing
* its underlying representation.
*/
class MyCollection {
items = []
constructor(items = []) {
this.items = items
}
add(item) {
this.items.push(item)
}
[Symbol.iterator]() {
let index = 0
let items = this.items
return {
next() {
if (index < items.length) {
return {
value: items[index++],
done: false,
}
} else {
return {
done: true,
}
}
},
}
}
}
// usage
const collection = new MyCollection(['item1', 'item2'])
collection.add('item3')
for (const item of collection) {
console.log(item)
}
// item1
// item2
// item3
// alternate usage
const iterator = collection[Symbol.iterator]()
console.log(iterator.next()) // { value: 'item1', done: false }
console.log(iterator.next()) // { value: 'item2', done: false }
console.log(iterator.next()) // { value: 'item3', done: false }
console.log(iterator.next()) // { done: true }
// generator
function* myGenerator(collection) {
let index = 0
while (index < collection.length) {
yield collection[index++]
}
}
const gen = myGenerator(['one', 'two', 'three'])
for (const item of gen) {
console.log(item)
}
// one
// two
// three