copyWithSwapped method

List<T> copyWithSwapped(
  1. int index1,
  2. int index2
)

Returns a copy with elements swapped at two indices

Implementation

List<T> copyWithSwapped(int index1, int index2) {
  if (index1 < 0 || index1 >= length) {
    throw RangeError('index1 $index1 out of bounds');
  }
  if (index2 < 0 || index2 >= length) {
    throw RangeError('index2 $index2 out of bounds');
  }
  if (index1 == index2) return List.of(this);

  final newList = List<T>.from(this);
  final temp = newList[index1];
  newList[index1] = newList[index2];
  newList[index2] = temp;
  return newList;
}