Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ES6, there is iterator.next(); is there any way to supply iterator.previous()?

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())?

like image 400
Armeen Harwood Avatar asked Mar 10 '16 16:03

Armeen Harwood


People also ask

Which method is used by an iterator object to return a value in ES6?

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 .

How does iterator work in JavaScript?

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.

Which object method returns an iterable that can be used to iterate over the properties of an object?

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.

How do you write a for loop in ES6?

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 .


1 Answers

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.

like image 62
thefourtheye Avatar answered Oct 20 '22 20:10

thefourtheye