Partition - split iterables based on predicates

Pub Style: Pedantic FOSSA Status CI

Splits one list into two; no more, no less

But how?

final source = Iterable<int>.generate(10);
final result = source.partition((i) => i.isEven);
print(result.matching); // [ 0, 2, 4, 6, 8 ]
print(result.nonMatching); // [ 1, 3, 5 ,7 ,9 ]

By default, partitioning will happen lazily. This means that every time you access either matching or nonMatching (even to check the length), it will iterate over the entire source iterable.

To partition eagerly (and only iterate over the source once):

final source = Iterable<int>.generate(10);
final result = source.partition((i) => i.isEven, lazy: false);
// alteratively: final result = source.partitionNow((i) => i.isEven);
print(result.matching); // [ 0, 2, 4, 6, 8 ]
print(result.nonMatching); // [ 1, 3, 5 ,7 ,9 ]

The PartitionResult that is returned is just a List<Iterable<T>> with a fixed length of 2, where the first element is an Iterable (or List if partitioning was eager) of all the elements that matched the predicate, and where the second iterable contains all the elements that did not match the predicate.

The PartitionResult will always have a length of 2, even if you tried to partition an empty source iterable or if nothing/everything matched the predicate.

License

FOSSA Status

Libraries

partition
Adds predicate partitioning support for iterables.