|
10 | 10 | 8. [Class](#class)
|
11 | 11 | 9. [Promises](#promises)
|
12 | 12 | 10. [Maps and Sets](#maps-and-sets)
|
| 13 | +11. [Iterables and iterators](#iterables-and-iterators) |
13 | 14 |
|
14 | 15 | ## Variable scope
|
15 | 16 |
|
@@ -1107,3 +1108,42 @@ ws.add(bar);
|
1107 | 1108 | ws.has(foo); // true
|
1108 | 1109 | ws.has(bar); // true
|
1109 | 1110 | ```
|
| 1111 | + |
| 1112 | +## Iterables and iterators |
| 1113 | +ES6 introduces a new mechanism for traversing data: iteration. Two concepts are central to iteration: |
| 1114 | +* An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators. |
| 1115 | +* An iterator is a pointer for traversing the elements of a data structure (think cursors in databases). |
| 1116 | + |
| 1117 | +`String`, `Array`, `TypedArray`, `Map` and `Set` are all built-in iterables, because each of their prototype objects implements an `@@iterator` method. |
| 1118 | + |
| 1119 | +### User-defined iterables |
| 1120 | +We can make our own iterables like this: |
| 1121 | +``` |
| 1122 | +var myIterable = {}; |
| 1123 | +myIterable[Symbol.iterator] = function* () { |
| 1124 | + yield 1; |
| 1125 | + yield 2; |
| 1126 | + yield 3; |
| 1127 | +}; |
| 1128 | +[...myIterable]; // [1, 2, 3] |
| 1129 | +``` |
| 1130 | +### Simple Iterator for an Array |
| 1131 | +``` |
| 1132 | +function makeIterator(array) { |
| 1133 | + var nextIndex = 0; |
| 1134 | + |
| 1135 | + return { |
| 1136 | + next: function() { |
| 1137 | + return nextIndex < array.length ? |
| 1138 | + {value: array[nextIndex++], done: false} : |
| 1139 | + {done: true}; |
| 1140 | + } |
| 1141 | + }; |
| 1142 | +} |
| 1143 | + |
| 1144 | +var it = makeIterator(['yo', 'ya']); |
| 1145 | + |
| 1146 | +console.log(it.next().value); // 'yo' |
| 1147 | +console.log(it.next().value); // 'ya' |
| 1148 | +console.log(it.next().done); // true |
| 1149 | +``` |
0 commit comments