{{ message }}

Instantly share code, notes, and snippets.

# ivan-kleshnin/swap.js

Last active May 17, 2019
 function swap(i1, i2, xs) { if (i1 == i2) return xs return xs.reduce((z, x, i) => { return i == i1 ? z : i == i2 ? (i1 > i2 ? [...z, xs[i1], x] : [...z, x, xs[i1]]) : [...z, x] }, []) } // Например, переставить 'B' с i1 = 1 на i2 = 4 // ['a', 'B', 'c', 'd', 'e', 'f'] => ['a', 'c', 'd', 'e', 'B', 'f'] console.log(swap(1, 4, ['a', 'B', 'c', 'd', 'e', 'f'])) console.log(['a', 'c', 'd', 'e', 'B', 'f']) // Переставить 'С' с i1 = 2 на i2 = 0 // ['a', 'b', 'С', 'd', 'e', 'f'] => ['С', 'a', 'b', 'd', 'e', 'f'] console.log(swap(2, 0, ['a', 'b', 'С', 'd', 'e', 'f'])) console.log(['С', 'a', 'b', 'd', 'e', 'f'])

### Ulgerd commented May 17, 2019

 ``````function swap (i1, i2, xs) { var result = []; xs.map((value, index) => { if (index === i1) return; if (index === i2) { (i1 > i2) ? result.push(arr[i1], value) : result.push(value, arr[i1]); return; } result.push(value); return; }); return result; } ``````

### Ulgerd commented May 17, 2019

 ``````function swap (i1, i2, xs) { var result = [...xs]; result.splice(i1, 1); result.splice(i2, 0, xs[i1]); return result; } ``````