replaceList<T> function

List<T> replaceList<T>(
  1. Iterable<T> it,
  2. bool replaceAll,
  3. T from, [
  4. dynamic to,
])

Delete first occurrence, or replace with to

Implementation

List<T> replaceList<T>(Iterable<T> it, bool replaceAll, T from, [dynamic to]) {
  if (it.isEmpty) {
    return [];
  }
  if (to is Iterable && to.isEmpty) {
    return replaceList(it, replaceAll, from);
  }

  if (to != null && to is! List<T> && to is! T) {
    throw ArgumentError('Replacement value must be $T or List<$T>.');
  }

  List<int> indicesToReplace = [];
  List<T> copy = List.from(it);
  for (int i in nums(it.length)) {
    if (deepEquals(copy[i], from)) {
      indicesToReplace.add(i);
      if (!replaceAll) {
        break;
      }
    }
  }

  if (to is Iterable<T>) {
    List<T> result = List.from(it);
    for (int i in backwardsList(indicesToReplace)) {
      result.removeAt(i);
      for (T j in backwardsList(to)) {
        result.insert(i, j);
      }
    }

    return result;
  }

  List<T> result = List.from(it);
  for (int i in backwardsList(indicesToReplace)) {
    to == null ? result.removeAt(i) : result[i] = to;
  }

  return result;
}