Skip to content

Instantly share code, notes, and snippets.

@timwis timwis/reorder.js
Last active Dec 25, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.