slice method Null safety
Returns a list slice from given list with all indices contained within the given range. START INCLUSIVE | END EXCLUSIVE. By default start=0, stop=list.length, step=1. Invalid inputs are met with ArgumentErrors. ex:
[0,1,2,3,4,5,6].slice(stop: 4) => [0,1,2,3]
Implementation
List<E> slice({int? stop, int start = 0, int step = 1}) {
//Defaults
stop ??= length; //TODO FIX NEG SLICE DEFAULT
List<E> iterationList = step.isPositive ? List<E>.from(this) : reversed.toList();
if (step.isNegative){step *= -1;}
//Clean Up Index (Negative and invalid start/stops)
while (start < 0) {
start += length;
}
while (stop! < 0) {
stop += length;
}
if (start > length || stop > length) {
throw ArgumentError(
'Either stop $stop or start $start is greater than the '
'length of this list $this | length: $length');
}
if (stop == 0){return <E>[];}
//Create new list and add things from range into the list
List<E> newList = [];
for (int i in range(stop, start: start, step: step)) {
newList.add(iterationList[i]);
}
return newList;
}