replace method

Queue<E> replace(
  1. Iterable<E> from,
  2. Iterable<E> to, {
  3. int? count,
  4. int skip = 0,
  5. bool reverse = false,
  6. dynamic recursive = false,
  7. bool equalityFunction(
    1. E a,
    2. E b
    ) = h.symmetricDeepEquals,
})

Replace from with to.

1, 2, 1, 2, 3.replace(1, 2, []) returns 3. 1, 1, 1, 1.replace(1, 1, 4) returns 4, 4.

Optional count replaces that many occurrences: 1, 2, 1, 2.replace(1, 2, [], count: 1) returns 1, 2.

High count replaces all occurrences: 1, 1, 1.replace(1, 2, count: 100) returns 2, 2, 2. count <= 0 returns original: 1, 1, 1.replace(1, 2, count: -100) returns 1, 1, 1.

Empty from means to is inserted before and after each element: 1, 1, 1.replace([], 2) returns 2, 1, 2, 1, 2, 1, 2. [].replace([], 1) returns 1.

Sometimes, removing elements can make the pattern reappear. recursive will cycle through to remove the pattern again, but will stop if number of occurrences or total length of iterable is not going down to avoid infinite loops:

3, 2, 2, 2, 1, 1, 1.replace(2, 1, [], recursive: true) returns 3.

If count is not null, recursive will only apply until count occurrences are removed: 3, 2, 2, 2, 1, 1, 1.replace(2, 1, [], recursive: true, count: 2) returns 3, 2, 1.

Default h.symmetricDeepEquals finds occurrences of from by checking DeepCollectionEquality().equals in both directions since it is normally asymmetric, but custom equalityFunction can be given that will compare elements in original to elements in from.

Implementation

Queue<E> replace(
  Iterable<E> from,
  Iterable<E> to, {
  int? count,
  int skip = 0,
  bool reverse = false,
  recursive = false,
  bool Function(E a, E b) equalityFunction = h.symmetricDeepEquals,
}) {
  return h
      .replaceIterable(
        original: this,
        from: from,
        to: to,
        count: count,
        recursive: recursive,
        skip: skip,
        reverse: reverse,
        equalityFunction: equalityFunction,
      )
      .toQueue();
}