mirror of
https://gitlab.com/nkming2/nc-photos.git
synced 2025-01-22 16:56:19 +01:00
Add step to List.slice
This commit is contained in:
parent
5243e300fb
commit
e6ed521a54
2 changed files with 24 additions and 3 deletions
|
@ -6,7 +6,8 @@ import 'package:nc_photos/int_extension.dart';
|
|||
extension ListExtension<T> on List<T> {
|
||||
Iterable<T> takeIndex(List<int> indexes) => indexes.map((e) => this[e]);
|
||||
|
||||
List<T> slice(int start, [int? stop]) {
|
||||
List<T> slice(int start, [int? stop, int step = 1]) {
|
||||
assert(step > 0);
|
||||
if (start < 0) {
|
||||
start = math.max(length + start, 0);
|
||||
}
|
||||
|
@ -16,11 +17,21 @@ extension ListExtension<T> on List<T> {
|
|||
if (start >= length) {
|
||||
return [];
|
||||
} else if (stop == null) {
|
||||
return sublist(start);
|
||||
final sub = sublist(start);
|
||||
if (step <= 1) {
|
||||
return sub;
|
||||
} else {
|
||||
return sub.whereIndexed((index, _) => index % step == 0).toList();
|
||||
}
|
||||
} else if (start >= stop) {
|
||||
return [];
|
||||
} else {
|
||||
return sublist(start, math.min(stop, length));
|
||||
final sub = sublist(start, math.min(stop, length));
|
||||
if (step <= 1) {
|
||||
return sub;
|
||||
} else {
|
||||
return sub.whereIndexed((index, _) => index % step == 0).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -70,6 +70,16 @@ void main() {
|
|||
test("-start +stop", () {
|
||||
expect(list.slice(-5, 9), List.generate(5, (i) => i + 5));
|
||||
});
|
||||
|
||||
/// Expected: [2, 4, 6, 8]
|
||||
test("step = 2", () {
|
||||
expect(list.slice(1, 9, 2), [2, 4, 6, 8]);
|
||||
});
|
||||
|
||||
/// Expected: [1]
|
||||
test("step = 10", () {
|
||||
expect(list.slice(1, 9, 9), [2]);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue