I am reading the book You don't know JS currently. When going over the section "Iterators of ES6", I came across the following piece of code
var Fib = {
[Symbol.iterator]() {
var n1 = 1, n2 = 1;
return {
// make the iterator an iterable
[Symbol.iterator]() { return this; },
next() {
var current = n2;
n2 = n1;
n1 = n1 + current;
return { value: current, done: false };
},
return(v) {
console.log(
"Fibonacci sequence abandoned."
);
return { value: v, done: true };
}
};
}
};
Here what is the purpose of making the iterator that is returned from the iterable Fib to be an iterable too ? In this Medium article the author states that
"Please note that this is the pattern followed by ES6 built-in iterators."
for making iterators in turn iterables. I have not found an explanation to this pattern or even use cases by searching the MDN docs or simply in Google. Can some one please point me in the right direction to know about this ?
The iterator object of the built-in iterable data types is itself iterable. (That is, it has a method with the symbolic name Symbol.iterator, which simply returns the object itself.) Sometimes this is useful in the following code when you want to run through a “partially used” iterator:
let list = [l,2,3,4,5];
let iter = list[Symbol.iterator]();
let head = iter.next().value; // head == 1
let tail = [...iter]; // tail == [2,3,4,5]
JavaScript: The Definitive Guide, David Flanagan, page 363
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With