/**
 * Swaps two elements in a list
 * @param list is the array in which you want to swap the items.
 * @param index1 index of the element you want to swap
 * @param index2 index of the element you want to swap
 * @returns a new list with the updated order after the swap operation
 *
 * @usage
 * ```typescript
 * const myList = [1, 2, 3, 4, 5];
 * swapItems(myList, 2, 4);
 * console.log(myList); // Output: [1, 2, 5, 4, 3]
 * ```
 */
export function swapItems<T>(list: T[], index1: number, index2: number): T[] {
  const _list = list.slice();
  if (
    index1 < 0 ||
    index1 >= _list.length ||
    index2 < 0 ||
    index2 >= _list.length
  ) {
    throw new Error('Invalid index');
  }

  const temp = _list[index1];
  _list[index1] = _list[index2];
  _list[index2] = temp;

  return _list;
}
