Skip to content

Instantly share code, notes, and snippets.

@togakangaroo
Created November 26, 2015 18:43
Show Gist options
  • Save togakangaroo/ba93717f5e8cd158beed to your computer and use it in GitHub Desktop.
Save togakangaroo/ba93717f5e8cd158beed to your computer and use it in GitHub Desktop.
// [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)
}
@togakangaroo
Copy link
Author

The specs:

describe('Switching array positions', () => {
    const array = [1, 2, 3, 4, 5]
    const moving = ({fromPosition, toPosition}, result) => () =>
        moveIntoPosition(array, fromPosition, toPosition).should.deep.equal(result)

    it('can reposition forward', moving({fromPosition: 2, toPosition: 3}, [1, 2, 4, 3, 5]) )
    it('can reposition backward', moving({fromPosition: 2, toPosition: 1}, [1, 3, 2, 4, 5]) )
    it('can reposition into the same position', moving({fromPosition: 2, toPosition: 2}, [1, 2, 3, 4, 5]) )
    it('can reposition into the first position', moving({fromPosition: 2, toPosition: 0}, [3, 1, 2, 4, 5]) )
    it('can reposition into the last position', moving({fromPosition: 2, toPosition: 4}, [1, 2, 4, 5, 3]) )
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment