const swap = (a,b) => (arr) => {
const aux = (i, [x, ...xs]) => {
if (x === undefined)
return []
else if (i === a)
return [arr[b], ...aux(i + 1, xs)]
else if (i === b)
return [arr[a], ...aux(i + 1, xs)]
else
return [x, ...aux(i + 1, xs)]
}
return aux (0, arr)
}
let xs = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
// same index doesn't matter
console.log(swap(0,0) (xs)) // [a, b, c, d, e, f, g]
// order doesn't matter
console.log(swap(0,1) (xs)) // [b, a, c, d, e, f, g]
console.log(swap(1,0) (xs)) // [b, a, c, d, e, f, g]
// more tests
console.log(swap(1,3) (xs)) // [a, c, d, b, e, f, g]
console.log(swap(0,6) (xs)) // [g, b, c, d, e, f, a]
console.log(swap(5,6) (xs)) // [a, b, c, d, e, g, f]
// don't fuck it up
console.log(swap(7,3) (xs)) // [a, b, c, undefined, e, f, g]
// empty list doesn't matter
console.log(swap(3,2) ([])) // []
可能的複製物品i一個JavaScript的數組](http://stackoverflow.com/questions/4011629/swapping-two-items-in-a-javascript-array) –
預期的結果是一個新的數組或在原始數組元素交換? – guest271314