以功能方式交换两个数组元素

Has*_*lef 3 javascript functional-programming

我试图在javascript中以函数方式交换数组中的2个元素(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]
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一方法是:

const swap = (arr, a, b) => 
            arr.map( (curr,i) => i === a ? arr[b] : curr )
               .map( (curr,i) => i === b ? arr[a] : curr )
Run Code Online (Sandbox Code Playgroud)

但是这个代码在数组上运行了两次,根本不可读.有什么好的干净功能代码的建议吗?

谢谢.

小智 8

简短而可靠,但难以理解:

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([])
);
Run Code Online (Sandbox Code Playgroud)

  • 看起来不错!,虽然不实用。这种方法的核心工作依赖于变异 (3认同)

web*_*deb 5

一张“地图”也可以做到:

function swap(arr, a, b) {
  return arr.map((current, idx) => {
    if (idx === a) return arr[b]
    if (idx === b) return arr[a]
    return current
  });
}
Run Code Online (Sandbox Code Playgroud)