takeLast method
Returns a new list containing the last n elements from this iterable.
This function checks if the current iterable is already a list. If it is, it operates directly on it.
Otherwise, it converts the iterable to a list and then returns the last n elements.
If n is greater than the length of the iterable, it returns as many elements as available.
Parameters: n (int): The number of elements to take from the end of the iterable.
Returns: List
Throws:
ArgumentError: If n is negative.
Example:
List<int> numbers = [1, 2, 3, 4, 5];
List<int> lastTwo = numbers.takeLast(2); // Returns [4, 5]
Note:
If n is 0, an empty list is returned. If n is greater than the number of elements in the iterable,
all elements are returned without causing an error.
Implementation
List<T> takeLast(int n) {
if (n < 0) {
throw ArgumentError('Negative value not allowed for n: $n');
}
var list = this is List<T> ? this as List<T> : toList();
int start = n < list.length ? list.length - n : 0;
return list.sublist(start);
}