Going through the full ES6 Compatibility table. Just got on to Set()
.
const set = new Set();
set.add('foo');
set.add('baz');
const iterator = set.values();
iterator.next(); // { value: "foo", done: false }
iterator.next(); // { value: "baz", done: false }
Is it possible to write a method similar to iterator.next()
, but it iterates backwards instead of forwards (i.e. iterator.previous()
)?
The [Symbol. iterator]() can be used to retrieve an iterator object. The next() method of the iterator returns an object with 'value' and 'done' properties .
In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value. The next value in the iteration sequence.
21.3. For example, all major ES6 data structures (Arrays, Typed Arrays, Maps, Sets) have three methods that return iterable objects: entries() returns an iterable over entries encoded as [key, value] Arrays. For Arrays, the values are the Array elements and the keys are their indices.
A for – of loop starts by calling the [Symbol. iterator]() method on the collection. This returns a new iterator object. An iterator object can be any object with a .
The values()
returns an iterator object and it is not possible to iterate them backwards, because JavaScript iterator objects could be infinite. For example, consider this
function * Counter() {
"use strict";
var i = 0;
while (1) {
yield i++;
}
}
Now, you can create an iterator with Counter()
and that will never end. So going backwards is not an option with iterators, generally.
If you badly need something like backIterator, then you have to maintain the values produced by the iterator and then move back and forth based on the next
calls.
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