I have function as follows:
export const updatePriorities = (data, draggedItem, targetItem) => {
const draggedItemPriority = draggedItem?.priority;
const targetItemPriority = targetItem?.priority;
if (draggedItemPriority === undefined || targetItemPriority === undefined || draggedItemPriority === null || targetItemPriority === null) {
return data;
}
const minPriority = Math.min(draggedItemPriority, targetItemPriority);
const maxPriority = Math.max(draggedItemPriority, targetItemPriority);
const newData = map(data, (item) => {
if (item.priority === draggedItemPriority) {
return { ...item, priority: targetItemPriority };
} else if (item.priority >= minPriority && item.priority < maxPriority) {
const priorityOffset = targetItemPriority < draggedItemPriority ? 1 : -1;
return { ...item, priority: item.priority + priorityOffset };
} else if (item.priority === targetItemPriority) {
return { ...item, priority: draggedItemPriority };
}
return item;
});
return orderBy(newData, 'priority');
};
My data is as follows:
const mockedData = [
{ name: 'Item 0', priority: 0 },
{ name: 'Item 1', priority: 1 },
{ name: 'Item 2', priority: 2 },
{ name: 'Item 3', priority: 3 },
{ name: 'Item 4', priority: 4 },
{ name: 'Item 5', priority: 5 }
];
const mockedDraggedItem1 = mockedData[1];
const mockedTargetItem1 = mockedData[3];
But updatePriorities(mockedData, mockedDraggedItem1, mockedTargetItem1)
gives me:
[
{name: "Item 0", priority: 0}
{name: "Item 2", priority: 1}
{name: "Item 3", priority: 1}
{name: "Item 1", priority: 3}
{name: "Item 4", priority: 4}
{name: "Item 5", priority: 5}
]
instead of
[
{name: "Item 0", priority: 0}
{name: "Item 2", priority: 1}
{name: "Item 3", priority: 2}
{name: "Item 1", priority: 3}
{name: "Item 4", priority: 4}
{name: "Item 5", priority: 5}
]
The priority of the mockedTargetItem1
is not updated correctly.
If the priority of draggedItem
is higher then priority of targetItem
then it works fine, but if priority of targetItem
is higher than priority of draggedItem
then it does not works as it should.
Any idea?
2
Answers
Use (working)
instead of (bad)
therefore, don’t need to
consider using lodash sortBy for this use case and for all your arrays operations.