mirror of
https://github.com/cypherstack/stack_wallet.git
synced 2024-12-22 19:39:22 +00:00
chunked list extension
This commit is contained in:
parent
c7c34803fa
commit
c7e7643fe5
2 changed files with 52 additions and 0 deletions
19
lib/utilities/extensions/impl/list.dart
Normal file
19
lib/utilities/extensions/impl/list.dart
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
extension ListExt<T> on List<T> {
|
||||||
|
List<List<T>> chunked({required int chunkSize}) {
|
||||||
|
final remainder = length % chunkSize;
|
||||||
|
final count = length ~/ chunkSize;
|
||||||
|
final List<List<T>> result = [];
|
||||||
|
|
||||||
|
int i = 0;
|
||||||
|
while (i < count) {
|
||||||
|
result.add(sublist(i, i + chunkSize));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainder > 0) {
|
||||||
|
result.add(sublist(i, i + remainder));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
33
test/utilities/extensions/list_test.dart
Normal file
33
test/utilities/extensions/list_test.dart
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:stackwallet/utilities/extensions/extensions.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test("Empty list", () {
|
||||||
|
final List<int> list = [];
|
||||||
|
expect(
|
||||||
|
list.chunked(chunkSize: 3).isEmpty,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("No remainder", () {
|
||||||
|
final List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8];
|
||||||
|
final chunked = list.chunked(chunkSize: 3);
|
||||||
|
expect(chunked.length == 3, true);
|
||||||
|
expect(
|
||||||
|
chunked.map((e) => e.length == 3).reduce((v, e) => v && e),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Some remainder", () {
|
||||||
|
final List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||||
|
final chunked = list.chunked(chunkSize: 3);
|
||||||
|
expect(chunked.length == 4, true);
|
||||||
|
expect(chunked.last.length == 1, true);
|
||||||
|
expect(
|
||||||
|
chunked.map((e) => e.length == 3).reduce((v, e) => v && e),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
Loading…
Reference in a new issue