Slice lists

This commit is contained in:
Ming Ming 2022-01-02 01:25:50 +08:00
parent c26fa28594
commit 98b540ea48
2 changed files with 85 additions and 0 deletions

View file

@ -1,3 +1,23 @@
import 'dart:math' as math;
extension ListExtension<T> on List<T> {
Iterable<T> takeIndex(List<int> indexes) => indexes.map((e) => this[e]);
List<T> slice(int start, [int? stop]) {
if (start < 0) {
start = math.max(length + start, 0);
}
if (stop != null && stop < 0) {
stop = math.max(length + stop, 0);
}
if (start >= length) {
return [];
} else if (stop == null) {
return sublist(start);
} else if (start >= stop) {
return [];
} else {
return sublist(start, math.min(stop, length));
}
}
}

View file

@ -6,5 +6,70 @@ void main() {
test("takeIndex", () {
expect([1, 2, 3, 4, 5, 6].takeIndex([5, 4, 3, 1, 0]), [6, 5, 4, 2, 1]);
});
group("slice", () {
// [1, ..., 9]
final list = List.generate(9, (i) => i + 1);
/// Expected: [4, ..., 9]
test("+start", () {
expect(list.slice(3), List.generate(6, (i) => i + 4));
});
/// Expected: []
test("+start > length", () {
expect(list.slice(999), const []);
});
/// Expected: [4, 5]
test("+start +stop", () {
expect(list.slice(3, 5), const [4, 5]);
});
/// Expected: [4, ..., 9]
test("+start +stop > length", () {
expect(list.slice(3, 999), List.generate(6, (i) => i + 4));
});
/// Expected: []
test("+start > +stop", () {
expect(list.slice(5, 3), const []);
});
/// Expected: [5, ..., 9]
test("-start", () {
expect(list.slice(-5), List.generate(5, (i) => i + 5));
});
/// Expected: [1, ..., 9]
test("-start < -length", () {
expect(list.slice(-999), List.generate(9, (i) => i + 1));
});
/// Expected: [5, 6]
test("-start -stop", () {
expect(list.slice(-5, -3), const [5, 6]);
});
/// Expected: []
test("-start -stop < -length", () {
expect(list.slice(-5, -999), const []);
});
/// Expected: []
test("-start < -stop", () {
expect(list.slice(-3, -5), const []);
});
/// Expected: [4]
test("+start -stop", () {
expect(list.slice(3, -5), [4]);
});
/// Expected: [5, ..., 9]
test("-start +stop", () {
expect(list.slice(-5, 9), List.generate(5, (i) => i + 5));
});
});
});
}