forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_3_list_iteration.js
More file actions
58 lines (50 loc) · 1.07 KB
/
Copy path06_3_list_iteration.js
File metadata and controls
58 lines (50 loc) · 1.07 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
class ListIterator {
constructor(list) {
this.list = list;
}
next() {
if (this.list == List.empty) return {done: true};
let result = {value: this.list.value, done: false};
this.list = this.list.rest;
return result;
}
}
// Class mostly from the previous exercise
class List {
constructor(value, rest) {
this.value = value;
this.rest = rest;
}
toArray() {
let array = [];
for (let list = this; list != List.empty; list = list.rest) {
array.push(list.value);
}
return array;
}
get length() {
let length = 0;
for (let list = this; list != List.empty; list = list.rest) {
length++;
}
return length;
}
static fromArray(array) {
let list = List.empty;
for (let i = array.length - 1; i >= 0; i--) {
list = new List(array[i], list);
}
return list;
}
// New code:
[Symbol.iterator]() {
return new ListIterator(this);
}
}
List.empty = new List(undefined, undefined);
for (let value of List.fromArray(["a", "b", "c"])) {
console.log(value);
}
// → a
// → b
// → c