Last active
November 10, 2021 07:07
-
-
Save PlugFox/cd8ba4736c95ada1ab2fe4d3ed220a33 to your computer and use it in GitHub Desktop.
ChunkWhile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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