Skip to content

Instantly share code, notes, and snippets.

@SourceCode
Last active August 20, 2017 00:35
Show Gist options
  • Save SourceCode/a301980133aed4ae0259557b5463bd72 to your computer and use it in GitHub Desktop.
Save SourceCode/a301980133aed4ae0259557b5463bd72 to your computer and use it in GitHub Desktop.
Move and sort x, y coordinates in a grid of objects
//This sorts a list of x,y cords for moving points
const cords = [
{ id: 1, x: 1, y: 1 },
{ id: 2, x: 1, y: 2 },
{ id: 3, x: 1, y: 3 },
{ id: 4, x: 1, y: 4 },
{ id: 5, x: 2, y: 1 },
{ id: 6, x: 2, y: 2 },
{ id: 7, x: 2, y: 3 },
{ id: 8, x: 2, y: 4 },
{ id: 9, x: 3, y: 1 },
{ id: 10, x: 3, y: 2 },
{ id: 11, x: 3, y: 3 },
{ id: 12, x: 3, y: 4 },
];
//console.log(cords);
function sort(cords, moveX, moveY, curX, curY) {
const moveItem = _.filter(cords, { x: curX, y: curY})
return cords.map(function(item) {
const sameRow = (curX === moveX);
//Update the moving item
if (item.id === moveItem[0].id) {
return {
...item,
x: moveX,
y: moveY
}
}
if (sameRow && item.x === curX) { //moving in same row and items are in same row
if (moveY > curY) { //moving up
if (item.y <= moveY && item.y > curY) {
return {
...item,
y: --item.y
}
}
} else if (moveY < curY) { //moving down
if (item.y >= moveY && item.y < curY) {
return {
...item,
y: ++item.y
}
}
}
} else { //move to diff row
if (item.x === curX) { //handle items in old row
if (item.y > curY) {
return {
...item,
y: --item.y
}
}
} else if (item.x === moveX) { //handle items in my new row
if (item.y >= moveY) {
return {
...item,
y: ++item.y
}
}
}
}
return item;
});
}
let cords2 = sort(cords, 2, 4, 1, 3);
console.log('final sort', cords2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment