takeFirst method
Returns a new list containing the first 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 first 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 beginning of the iterable.
Returns: List
Throws:
ArgumentError: If n is negative.
Example:
List<int> numbers = [1, 2, 3, 4, 5];
List<int> firstThree = numbers.takeFirst(3); // Returns [1, 2, 3]
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> takeFirst(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 end = n < list.length ? n : list.length;
return list.sublist(0, end);
}