Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active November 10, 2021 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugFox/cd8ba4736c95ada1ab2fe4d3ed220a33 to your computer and use it in GitHub Desktop.
Save PlugFox/cd8ba4736c95ada1ab2fe4d3ed220a33 to your computer and use it in GitHub Desktop.
ChunkWhile
/*
* Expando with method extension
* https://gist.github.com/PlugFox/cd8ba4736c95ada1ab2fe4d3ed220a33
* https://dartpad.dev/cd8ba4736c95ada1ab2fe4d3ed220a33?id=&null_safety=true
*/
void main() {
final list = <int>[1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21];
print('chunkWhile:');
list.chunkWhile((a, b) => a + 1 == b).forEach(print);
print('\n' 'splitWhen:');
list.splitWhen((a, b) => a + 1 == b).forEach(print);
}
extension ChunkWhileX<T extends Object?> on Iterable<T> {
Iterable<List<T>> chunkWhile(bool Function(T a, T b) test) sync* {
final i = iterator;
var list = i.moveNext() ? <T>[i.current] : <T>[];
while (i.moveNext()) {
if (test(list.last, i.current)) {
list.add(i.current);
} else {
yield list;
list = <T>[i.current];
}
}
if (list.isNotEmpty) yield list;
}
Iterable<List<T>> splitWhen(bool Function(T a, T b) test) =>
chunkWhile((a, b) => !test(a, b));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment