mapIndexed<R> method

Iterable<R> mapIndexed<R>(
  1. R transform(
    1. int index,
    2. T
    )
)

Returns a new lazy Iterable containing only the non-null results of applying the given transform function to each element in the original collection. Returns a new lazy Iterable containing the results of applying the given transform function to each element of this collection, where the function takes two arguments: the index of the current element and the element itself.

The transform function is invoked for each element in the collection with two arguments: the index of the current element and the element itself. The result of the transform function is included in the resulting iterable.

  • Parameters:

    • transform: A function that takes an integer index and an element of type T and returns a result of type R.
  • Returns: A new lazy Iterable containing the results of applying the transform function to each element of this collection.

  • Example:

    Iterable<String> fruits = ['apple', 'banana', 'cherry'];
    Iterable<String> upperCaseFruits = fruits.mapIndexed((index, fruit) {
      return '$index: ${fruit.toUpperCase()}';
    });
    
    print(upperCaseFruits); // Output: ['0: APPLE', '1: BANANA', '2: CHERRY']
    

Note: This method creates a new lazy Iterable and does not modify the original collection. It allows you to transform elements based on their index within the collection.

Implementation

/// Returns a new lazy [Iterable] containing the results of applying the given
/// [transform] function to each element of this collection, where the function
/// takes two arguments: the index of the current element and the element itself.
///
/// The [transform] function is invoked for each element in the collection with
/// two arguments: the index of the current element and the element itself.
/// The result of the [transform] function is included in the resulting iterable.
///
/// - Parameters:
///   - transform: A function that takes an integer index and an element of type
///     [T] and returns a result of type [R].
///
/// - Returns: A new lazy [Iterable] containing the results of applying the
///   [transform] function to each element of this collection.
///
/// - Example:
///   ```dart
///   Iterable<String> fruits = ['apple', 'banana', 'cherry'];
///   Iterable<String> upperCaseFruits = fruits.mapIndexed((index, fruit) {
///     return '$index: ${fruit.toUpperCase()}';
///   });
///
///   print(upperCaseFruits); // Output: ['0: APPLE', '1: BANANA', '2: CHERRY']
///   ```
///
/// Note:
/// This method creates a new lazy [Iterable] and does not modify the original
/// collection. It allows you to transform elements based on their index within
/// the collection.

Iterable<R> mapIndexed<R>(R Function(int index, T) transform) sync* {
  var index = 0;
  for (var element in this) {
    yield transform(index++, element);
  }
}