Skip to content

Instantly share code, notes, and snippets.

@timwis
Last active December 25, 2016 18:58
Show Gist options
  • Save timwis/80fa4196d7c4ffd206d132bf70a0af9e to your computer and use it in GitHub Desktop.
Save timwis/80fa4196d7c4ffd206d132bf70a0af9e to your computer and use it in GitHub Desktop.
function reorder (state, data) {
const { from, to } = data
const rowsCopy = state.rows.slice()
const fromRowCopy = rowsCopy[from.row].slice()
const item = fromRowCopy[from.index]
fromRowCopy.splice(from.index, 1) // remove from row
rowsCopy[from.row] = fromRowCopy // replace 'from' row
const toRowCopy = rowsCopy[to.row].slice()
toRowCopy.splice(to.index, 0, item) // add to row
rowsCopy[to.row] = toRowCopy // replace 'to' row
return { rows: rowsCopy }
}
test('move column between rows', (t) => {
t.plan(1)
const state = Object.freeze({
rows: [
[ {a: 'a'}, {b: 'b'}, {c: 'c'} ], // move b from here
[ {d: 'd'}, {e: 'e'} ]
]
})
const expected = {
rows: [
[ {a: 'a'}, {c: 'c'} ],
[ {d: 'd'}, {b: 'b'}, {e: 'e'} ] // to here
]
}
const payload = {
from: { row: 0, index: 1 },
to: { row: 1, index: 1 }
}
const result = reorder(state, payload)
t.deepEqual(result, expected)
})
test('move column within same row', (t) => {
t.plan(1)
const state = Object.freeze({
rows: [
[ {a: 'a'}, {b: 'b'}, {c: 'c'} ],
[ {d: 'd'}, {e: 'e'} ]
]
})
const expected = {
rows: [
[ {a: 'a'}, {c: 'c'}, {b: 'b'} ],
[ {d: 'd'}, {e: 'e'} ]
]
}
const payload = {
from: { row: 0, index: 1 },
to: { row: 0, index: 2 }
}
const result = reorder(state, payload)
t.deepEqual(result, expected)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment