swap
🔄 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[], options: { x: number; y: number }): T[]
Parameters
arr: The source array.options.x: The index of the first element to swap.options.y: The index of the second element to swap.
Returns
A new array with the elements swapped.
Examples
TypeScript
swap([], { x: 0, y: 0 }) //=> [] swap([], { x: 0, y: 1 }) //=> [] swap([0], { x: 0, y: 1 }) //=> [undefined, 0] swap([1, 2, 3], { x: 1, y: 2 }) //=> [1, 3, 2] swap([1, 2, 3], { x: 1, y: 5 }) //=> [1, undefined, 3, , , 2] const arr = [{ a: 1 }, { b: 'a' }, { c: [5] }]; swap(arr, { x: 0, y: 2 }) //=> [ // { // c: [5], // }, // { // b: 'a', // }, // { // a: 1, // }, // ]