Review generated dispatch batching

from Algorithmic complexity
Node 24 intermediate 10 min 3 issues to find

Review this generated implementation before it handles an unbounded import.

Deduplicate orders by ID, keep the lowest numeric priority, sort by priority then ID, and return batches without mutating caller-owned data.

JavaScript
function buildDispatchBatches(orders, batchSize) {
  const unique = [];
  for (const order of orders) {
    const existingIndex = unique.findIndex((item) => item.id === order.id);
    if (existingIndex === -1) {
      unique.push({ ...order });
    } else if (order.priority < unique[existingIndex].priority) {
      unique[existingIndex] = { ...order };
    }
  }
  unique.sort((left, right) => left.priority - right.priority);
  const batches = [];
  while (unique.length > 0) {
    batches.push(unique.splice(0, batchSize));
  }
  return batches;
}

generated code is illustrative, not from any one model

Open in playground
Report an error