# Iterator

# What is it

  • Iterable data structures has a [Symbol.iterator] method
  • Return a object after [Symbol.iterator] executed
  • iterator object has a next method
  • Return a object that has 2 properties: value and done, When next has been executed(a iterator used)

# DIY a iterator

function myIterator(items) {
  var i = 0;
  return {
    next: function() {
      var done = i >= items.length;
      var value = !done ? items[i++] : undefined;
      return {
        done: done,
        value: value
      };
    }
  };
}

var iterator1 = new myIterator([1, 2, 3]);
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());

// {done: false, value: 1}
// {done: false, value: 2}
// {done: false, value: 3}
// {done: true, value: undefined}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24