keyInList method
Checks if the index is within the bounds of the iterable.
This method verifies whether the iterable contains an element at the specified index.
It iterates over the iterable until it reaches the specified index or the end of the iterable,
which is more efficient than converting the iterable to a list or map.
This approach is particularly useful for large iterables as it avoids creating new collections.
-
Parameters:
index: The index to check within the iterable.
-
Returns: A boolean value,
trueif the index is within the bounds of the iterable; otherwise,false. -
Examples:
List<int> numbers = [10, 20, 30, 40, 50]; bool exists = numbers.keyInList(2); // true, since index 2 (element 30) exists bool notExists = numbers.keyInList(5); // false, since index 5 does not exist
Implementation
bool keyInList(int index) {
int count = 0;
for (var _ in this) {
if (count == index) {
return true;
}
count++;
}
return false;
}