Skip to content

Commit

Permalink
perf: Bring back custom iterator implementation of the iterator method
Browse files Browse the repository at this point in the history
  • Loading branch information
luanpotter committed Sep 8, 2024
1 parent 128c240 commit 3323b4b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion example/ordered_set_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ class Person {
int age;
String name;
Person(this.age, this.name);
}
}
29 changes: 28 additions & 1 deletion lib/ordered_set.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class OrderedSet<E> extends IterableMixin<E> {

@override
Iterator<E> get iterator {
return _backingSet.expand<E>((es) => es).iterator;
return _OrderedSetIterator<E>(this);
}

/// The tree's elements in reversed order, cached when possible.
Expand Down Expand Up @@ -170,3 +170,30 @@ class OrderedSet<E> extends IterableMixin<E> {
_length = 0;
}
}

class _OrderedSetIterator<E> implements Iterator<E> {
final Iterator<Set<E>> _iterator;
Iterator<E>? _innerIterator;

_OrderedSetIterator(OrderedSet<E> orderedSet)
: _iterator = orderedSet._backingSet.iterator;

@override
E get current => _innerIterator!.current;

@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
@override
bool moveNext() {
if (_innerIterator?.moveNext() != true) {
final result = _iterator.moveNext();

if (result) {
_innerIterator = _iterator.current.iterator..moveNext();
}

return result;
}
return true;
}
}

0 comments on commit 3323b4b

Please sign in to comment.