-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate-iterator.js
55 lines (43 loc) · 1.52 KB
/
Create-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
/*
Implement an iterator which receives an array of values, and returns an object with:
a function next
a number index
A call to the next function should return an object with 2 attributes:
value (the next value in the input array; undefined if the value is not present or the array has been fully processed)
done (boolean which specifies whether the input array has been fully processed)
Accessing the index attribute should return the index of the value currently held by the iterator.
Example:
const iterator = createIterator(['One', , 'Two']);
iterator.index // 0
iterator.next() // { value: 'One', done: false }
iterator.index // 1
// A hole in the array - value is undefined
iterator.next() // { value: undefined, done: false }
iterator.index // 2
iterator.next() // { value: 'Two', done: false }
iterator.index // 3
// Iteration has finished - value is undefined, done becomes true
iterator.next() // { value: undefined, done: true }
iterator.index // 3
// Subsequent calls to next of a fully processed iterator don't change anything
iterator.next() // { value: undefined, done: true }
iterator.index // 3
*/
// Answer:
const createIterator = (array) => {
return new Iterator(array)
};
class Iterator {
constructor(array) {
this.array = array;
this.index = 0;
}
next() {
if (this.index + 1 > this.array.length) {
return { value: undefined, done: true};
}
this.index++;
return { value: this.array[this.index - 1], done: false};
}
}
// BigO: O(n)