This function swaps two items in an array based on their indices.
JavaScript:
let swapItems = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]], arr);
// Example
console.log(swapItems(['a', 'b', 'c', 'd', 'e'], 1, 3)); // ['a', 'd', 'c', 'b', 'e']
console.log(swapItems([1, 2, 3, 4, 5], 0, 4)); // [5, 2, 3, 4, 1]
TypeScript:
let swapItems = (arr: T[], i: number, j: number): T[] => ([arr[i], arr[j]] = [arr[j], arr[i]], arr);
// Example
console.log(swapItems(['a', 'b', 'c', 'd', 'e'], 1, 3)); // ['a', 'd', 'c', 'b', 'e']
console.log(swapItems([1, 2, 3, 4, 5], 0, 4)); // [5, 2, 3, 4, 1]