Search code examples
javascriptfunctional-programming

Swap two array elements in a functional way


I'm trying to swap 2 elements within an array in a functional way in javascript (es6)

let arr = [1,2,3,4,5,6]
let result = swap(arr, 1, 2) // input: array, first element, second element
// result=[1,3,2,4,5,6]

The only way I could think about is:

const swap = (arr, a, b) => 
            arr.map( (curr,i) => i === a ? arr[b] : curr )
               .map( (curr,i) => i === b ? arr[a] : curr )

But this code runs twice over the array, and not readable at all. Any suggestions for a nice clean functional code?

Thanks.


Solution

  • Short and reliable but admittedly hard to read:

    const swap = (x, y) => ([...xs]) => xs.length > 1
     ? ([xs[x], xs[y]] = [xs[y], xs[x]], xs)
     : xs;
    
    const xs = [1,2,3,4,5];
    
    const swap12 = swap(1, 2);
    
    console.log(
      swap12(xs),
      "exception (one element):",
      swap12([1]),
      "exception (empty list):",
      swap12([])
    );