Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Created February 5, 2016 20:54
Show Gist options
  • Save andrewbranch/bf23a3e6deb104fb7cd8 to your computer and use it in GitHub Desktop.
Save andrewbranch/bf23a3e6deb104fb7cd8 to your computer and use it in GitHub Desktop.
#algorithm challenge: more elegant way to do this
import { describe, it, beforeEach } from 'mocha';
import assert from 'assert';
import transposeArray from './transpose-array';
describe('transpose-array', () => {
let array;
beforeEach(() => array = [0, 1, 2, 3, 4, 5]);
it('works for downward transpositions', () => {
let result = transposeArray(array, 4, 2);
assert.deepEqual(result, [0, 1, 4, 2, 3, 5]);
});
it('works for upward transpositions', () => {
let array = [0, 1, 2, 3, 4, 5];
let result = transposeArray(array, 1, 4);
assert.deepEqual(result, [0, 2, 3, 4, 1, 5]);
});
it('works at the lower bound', () => {
let result = transposeArray(array, 0, 3);
assert.deepEqual(result, [1, 2, 3, 0, 4, 5]);
});
it('works at the upper bound', () => {
let result = transposeArray(array, 5, 3);
assert.deepEqual(result, [0, 1, 2, 5, 3, 4]);
});
it('works from the lower bound to the upper bound', () => {
let result = transposeArray(array, 0, 5);
assert.deepEqual(result, [1, 2, 3, 4, 5, 0]);
});
it('works from the upper bound to the lower bound', () => {
let result = transposeArray(array, 5, 0);
assert.deepEqual(result, [5, 0, 1, 2, 3, 4]);
});
});
export default function transposeArray(array, from, to) {
let itemMoved = array[from],
movedUp = to > from,
lower = movedUp ? from : to,
upper = movedUp ? to : from;
return movedUp ? [
...array.slice(0, lower),
...array.slice(lower + 1, upper + 1),
itemMoved,
...array.slice(upper + 1)
] : [
...array.slice(0, lower),
itemMoved,
...array.slice(lower, upper),
...array.slice(upper + 1)
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment