swap
Swaps the positions of two elements in an array, either mutating the original array or returning a new array depending on the options.
Code
Interface
typescript
function swap<T>(
arr: T[] | readonly T[],
i: number,
j: number,
options?: { immutable?: boolean }
): T[]
Usage
Basic Usage (mutates original array)
typescript
import { swap } from '@modern-kit/utils';
const arr = [1, 2, 3];
swap(arr, 0, 2); // [3, 2, 1]
console.log(arr); // [3, 2, 1] (original array is mutated)
immutable option (returns new array)
typescript
import { swap } from '@modern-kit/utils';
const arr = [1, 2, 3];
const newArr = swap(arr, 0, 2, { immutable: true }); // [3, 2, 1]
console.log(arr); // [1, 2, 3] (original array preserved)
console.log(newArr); // [3, 2, 1] (new array returned)