update post: How does in-built Array iterator work?

This commit is contained in:
2020-07-16 10:36:17 +05:30
parent 7797cbdccd
commit 77d166065e
+1 -3
View File
@@ -13,12 +13,10 @@ When we use spread operator, like `[...someArray]` - it treats someArray as a ge
2. Then it consumes all the values from the iterable by calling `iter.next()` repeatedly. 2. Then it consumes all the values from the iterable by calling `iter.next()` repeatedly.
This method `.next()` returns response in this structure `{value: "something", done: true|false}`. This method `.next()` returns response in this structure `{value: "something", done: true|false}`.
3. While values are available, it returns `done: false`; after all values are finished, it returns `done: true`. After this, the consumer (i.e. spread operator) should stop asking for more values. 3. While values are available, it returns `done:false`; after all values are finished, it returns `done:true`. After this, the consumer (i.e. spread operator) should stop asking for more values.
This is how the iterable/iterator stuff works. This is how the iterable/iterator stuff works.
In our case, Iterable is `someArray` - which has a special property `Symbol.iterator` whose value is a method. Calling this method returns a iterable (`iter`), which has `.next()` method. Calling this method returns all the values one-by-one.
## Array Iterator ## Array Iterator
Array has in-built support for iterable/iterator protocol, through prototype. Array.prototype has a method with key `Symbol.iterator`, which creates a ArrayIterator. Array has in-built support for iterable/iterator protocol, through prototype. Array.prototype has a method with key `Symbol.iterator`, which creates a ArrayIterator.