Add step to List.slice

This commit is contained in:
Ming Ming 2022-10-11 00:05:53 +08:00
parent 5243e300fb
commit e6ed521a54
2 changed files with 24 additions and 3 deletions

View file

@ -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();
}
}
}

View file

@ -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]);
});
});
});
}