From c7e7643fe56cb26fae47dba843632241cf3394da Mon Sep 17 00:00:00 2001 From: julian Date: Thu, 30 May 2024 12:46:41 -0600 Subject: [PATCH] chunked list extension --- lib/utilities/extensions/impl/list.dart | 19 ++++++++++++++ test/utilities/extensions/list_test.dart | 33 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 lib/utilities/extensions/impl/list.dart create mode 100644 test/utilities/extensions/list_test.dart diff --git a/lib/utilities/extensions/impl/list.dart b/lib/utilities/extensions/impl/list.dart new file mode 100644 index 000000000..c802f2704 --- /dev/null +++ b/lib/utilities/extensions/impl/list.dart @@ -0,0 +1,19 @@ +extension ListExt on List { + List> chunked({required int chunkSize}) { + final remainder = length % chunkSize; + final count = length ~/ chunkSize; + final List> 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; + } +} diff --git a/test/utilities/extensions/list_test.dart b/test/utilities/extensions/list_test.dart new file mode 100644 index 000000000..594328034 --- /dev/null +++ b/test/utilities/extensions/list_test.dart @@ -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 list = []; + expect( + list.chunked(chunkSize: 3).isEmpty, + true, + ); + }); + + test("No remainder", () { + final List 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 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, + ); + }); +}