Created
November 26, 2015 18:43
-
-
Save togakangaroo/ba93717f5e8cd158beed to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// [1, 2, 3, 4, 5] => [1, 2, 3, 4, 5] | |
// [1, 2, 3, 4, 5], 2 => [1, 2], [2, 3, 5] | |
// [1, 2, 3, 4, 5], 2, 3 => [1, 2], [3], [4, 5] | |
// [1, 2, 3, 4, 5], 0, 3 => [], [1, 2, 3], [4, 5] | |
function* splitUp(arr, firstPivot, ...otherPivots) { | |
if(firstPivot === undefined) { | |
yield arr | |
return | |
} | |
const head = arr.slice(0, firstPivot) | |
const tail = arr.slice(firstPivot) | |
yield head | |
yield* splitUp(tail, ...otherPivots.map(x => x-firstPivot)) | |
} | |
// Will move element in the fromPosition index into the toPosition index (will not delete anything) | |
export const moveIntoPosition = (data, fromPosition, toPosition) => { | |
if(fromPosition === toPosition) | |
return data | |
const direction = fromPosition < toPosition ? +1 : -1 | |
const [before, [first], [second, ...after]] = Array.from( splitUp(data, ...[fromPosition, fromPosition+direction].sort()) ) | |
const newData = [...before, second, first, ...after] | |
return moveIntoPosition(newData, fromPosition+direction, toPosition) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The specs: