Created
December 29, 2022 04:20
-
-
Save alexcmgit/74de22b6b62af6c9915050f4c73c30bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import 'dart:math'; | |
extension ChunkedList<T> on List<T> { | |
/// Slice this list in chunks of a given [size]. | |
/// | |
/// If [size] is a negative number it will slice the reverse list of [this]. | |
/// | |
/// Set [incomplete] to `true` in order to include an incomplete chunk (if any). | |
/// | |
/// Usage: | |
/// ```dart | |
/// print(<int>[1, 2, 3, 4, 5].chunked(2, incomplete: false)); // [[1, 2], [3, 4]] | |
/// print(<int>[1, 2, 3, 4, 5].chunked(2, incomplete: true)); // [[1, 2], [3, 4], [5]] | |
/// print(<int>[1, 2, 3, 4, 5].chunked(-2, incomplete: false)); // [[5, 4], [3, 2]] | |
/// print(<int>[1, 2, 3, 4, 5].chunked(-2, incomplete: true)); // [[5, 4], [3, 2], [1]] | |
/// ``` | |
/// | |
/// Throws an [ArgumentError] if [size] is zero. | |
List<List<T>> chunked(int size, {bool incomplete = false}) { | |
if (size == 0) { | |
throw ArgumentError.value( | |
size, | |
'chunked', | |
'[size] must be a non-zero integer.', | |
); | |
} | |
final List<T> target = size.isNegative ? reversed.toList() : toList(); | |
final int n = size.abs(); | |
final int base = incomplete ? (length / n).ceil() : (length / n).floor(); | |
return <List<T>>[ | |
for (int i = 0; i < base; i++) | |
target.sublist(i * n, min((i + 1) * n, length)), | |
]; | |
} | |
} | |
void main() { | |
print(<int>[1, 2, 3, 4, 5].chunked(2, includeIncomplete: false)); // [[1, 2], [3, 4]] | |
print(<int>[1, 2, 3, 4, 5].chunked(2, includeIncomplete: true)); // [[1, 2], [3, 4], [5]] | |
print(<int>[1, 2, 3, 4, 5].chunked(-2, includeIncomplete: false)); // [[5, 4], [3, 2]] | |
print(<int>[1, 2, 3, 4, 5].chunked(-2, includeIncomplete: true)); // [[5, 4], [3, 2], [1]] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment