Last active
May 17, 2019 10:27
-
-
Save ivan-kleshnin/b115dc709c9a7c078a0f5e09119cc92e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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];
result.splice(i1, 1);
result.splice(i2, 0, xs[i1]);
return result;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment