Sometimes, we need to iterate over a collection of elements in both directions. To help in such cases, Dart provides BidirectionalIterator
. In the following code, BiListIterator
is the implementation of BidirectionalIterator
:
class BiListIterator<E> implements BidirectionalIterator<E> { final Iterable<E> _iterable; final int _length; int _index; E _current;
The constructor has an extra optional back
parameter that defines the direction of the iteration:
BiListIterator(Iterable<E> iterable, {bool back:false}) : _iterable = iterable, _length = iterable.length, _index = back ? iterable.length - 1 : 0; E get current => _current;
The following code shows the moveNext
method of the Iterator to move forward. This and the next method compare the length of the Iterable and the actual length of the collection to check concurrent modifications. The code is as follows:
bool moveNext() { int length = _iterable.length; if (_length != length) { throw new ConcurrentModificationError(_iterable); } if (_index >= length) { _current = null; return false; } _current = _iterable.elementAt(_index); _index++; return true; }
The following movePrevious
method of BidirectionalIterator
is used to move backwards:
bool movePrevious() { int length = _iterable.length; if (_length != length) { throw new ConcurrentModificationError(_iterable); } if (_index < 0) { _current = null; return false; } _current = _iterable.elementAt(_index); _index--; return true; } }
I have created a small example to prove that we can move in both directions:
main() { var list = new List.from([1, 2, 3, 4]); // Forward Iteration BiListIterator iter = new BiListIterator(list); while(iter.moveNext()) { print(iter.current); } // => 1, 2, 3, 4 // Backward Iteration iter = new BiListIterator(list, back:true); while(iter.movePrevious()) { print(iter.current); } // => 4, 3, 2, 1 }
First, I created an instance of List
, but it might be Set
or Queue
or any other collection that implements the Iterable interface. Then, I instantiated BiListIterator
and pointed it to my Iterable collection so that we are ready to traverse via elements of the collection in the forward direction. Later, I created another instance of BiListIterator
but specified the backward direction of the iteration. Finally, I could call movePrevious
to move in the backward direction.
18.119.106.237