elementAtOrDefaultE method

T elementAtOrDefaultE (int index, { T defaultValue })

Returns the element at the specified index or a default value of one is not found.

Iterates over the entire enumerable until it reaches the element on the iteration matching the given index. elementAtE will then return that value. If the iteration reaches the end of the enumerable before arriving at index, the value of defaultValue will be returned instead. If defaultValue is not supplied, the returned value will be null.

The elementAtOrDefaultE method will short-circuit after reaching the element at index and will not iterate further over the enumerable. In the worst case, it will iterate over the entire enumerable.

Implementation

T elementAtOrDefaultE(int index, {T defaultValue}) {
  assert(index >= 0);

  final iterator = this.iterator;
  int currentIndex = 0;
  while (iterator.moveNext()) {
    if (currentIndex == index) return iterator.current;
    currentIndex++;
  }

  return defaultValue;
}