Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Last active May 17, 2019 10:27
Show Gist options
  • Save ivan-kleshnin/b115dc709c9a7c078a0f5e09119cc92e to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/b115dc709c9a7c078a0f5e09119cc92e to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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