Why is this potion shelf shuffling the wrong bottle types?
function organizePotionShelf(slots, incomingBatch) {
const shelf = Array.from(slots);
const uncataloged = [];
for (const bottle of incomingBatch) {
if (bottle.tier < 1 || bottle.tier > 5) {
uncataloged.push(bottle);
continue;
}
const targetIndex = shelf.findIndex(
(slot) => slot && slot.tier === bottle.tier && !slot.sealed
);
if (targetIndex !== -1) {
shelf.splice(targetIndex, 1, bottle);
} else {
const emptyIdx = shelf.indexOf(null);
if (emptyIdx !== -1) {
shelf[emptyIdx] = bottle;
} else {
uncataloged.push(bottle);
}
}
}
const denseShelf = shelf.filter(Boolean);
const sortedByTier = denseShelf.toSorted((a, b) => a.tier - b.tier);
const reallocated = sortedByTier.reduce((acc, bottle, idx, arr) => {
if (idx === 0 || bottle.tier !== arr[idx - 1].tier) {
acc.push([bottle]);
} else {
acc.at(-1).push(bottle);
}
return acc;
}, []);
const flattenedDisplay = reallocated.flatMap((group) => {
const padded = new Array(3).fill(null);
return padded.map((_, i) => group[i] ?? { placeholder: true });
});
return {
slots: flattenedDisplay,
overflowCount: uncataloged.length
};
}
Reply with what is broken and how you would fix it.