-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathiterable.js
More file actions
61 lines (48 loc) · 1.02 KB
/
iterable.js
File metadata and controls
61 lines (48 loc) · 1.02 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
// https://javascript.info/iterable
let obj = {
from: 1,
to: 5
};
// The iterator object is separate from the object it iterates over:
obj[Symbol.iterator] = function () {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ }
} else {
return { done: true }
}
}
}
}
for (let n of obj) {
console.log(n);
}
// We may also use obj itself as the iterator to make the code simpler:
let obj2 = {
from: 10,
to: 15,
[Symbol.iterator]() {
this.current = this.from;
return this;
},
next() {
if (this.current <= this.to) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
for (let n of obj2) {
console.log(n);
}
// String is iterable:
for (let letter of 'hello') {
console.log(letter);
}
// Calling an iterator explicitly:
let str = 'world';
let iterator = str[Symbol.iterator](); // returns Object [String Iterator] {}