mutateSeparated<T> function

void mutateSeparated<T>(
  1. List<T> source,
  2. List<T> separatedList,
  3. T separator
)

Mutates a list to contain source elements with separators between them.

This function efficiently updates separatedList in place to match the pattern of source elements interleaved with separator values. It minimizes memory allocations by reusing existing list elements where possible.

Parameters

  • source - The source list of elements to separate.
  • separatedList - The list to mutate. Will be modified in place.
  • separator - The separator value to insert between source elements.

Side Effects

Modifies separatedList to contain elements from source with separator inserted between each pair of adjacent elements. If separatedList is too long, extra elements are removed. If too short, new elements are added.

Example

final source = [1, 2, 3];
final separated = <int>[];
mutateSeparated(source, separated, 0);
// separated is now [1, 0, 2, 0, 3]

// Update with new source
mutateSeparated([4, 5], separated, 0);
// separated is now [4, 0, 5]

Implementation

void mutateSeparated<T>(List<T> source, List<T> separatedList, T separator) {
  int targetIndex = 0; // Position in separatedList we're modifying

  for (int i = 0; i < source.length; i++) {
    // Update or add source element
    if (targetIndex < separatedList.length) {
      separatedList[targetIndex] = source[i];
    } else {
      separatedList.add(source[i]);
    }
    targetIndex++;

    // Update or add separator if not the last element
    if (i < source.length - 1) {
      if (targetIndex < separatedList.length) {
        separatedList[targetIndex] = separator;
      } else {
        separatedList.add(separator);
      }
      targetIndex++;
    }
  }

  // Remove extra elements if separatedList is too long
  if (targetIndex < separatedList.length) {
    separatedList.removeRange(targetIndex, separatedList.length);
  }
}