Created
February 5, 2016 20:54
-
-
Save andrewbranch/bf23a3e6deb104fb7cd8 to your computer and use it in GitHub Desktop.
#algorithm challenge: more elegant way to do this
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
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]); | |
}); | |
}); |
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
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