🔄 Swaps the positions of two elements in an array.
Info
Immutable: This function does not mutate the original array.
Syntax
TypeScript
import { swap } from '@opentf/std'; swap<T>(arr: T[], x: number, y: number): T[]
Parameters
arr: The source array.x: The index of the first element to swap.y: The index of the second element to swap.
Returns
A new array with the elements swapped.
Examples
TypeScript
swap([], 0, 0) //=> [] swap([], 0, 1) //=> [] swap([0], 0, 1) //=> [undefined, 0] swap([1, 2, 3], 1, 2) //=> [1, 3, 2] swap([1, 2, 3], 1, 5) //=> [1, undefined, 3, , , 2] const arr = [{ a: 1 }, { b: 'a' }, { c: [5] }]; swap(arr, 0, 2) //=> [ // { // c: [5], // }, // { // b: 'a', // }, // { // a: 1, // }, // ]