Most stock code picks batches by arrival date. For anything with an expiry date that is the wrong key: the batch that arrived first is not always the batch that runs out first.
The allocator
function allocate(batches, qty, rule) { const order = [...batches].sort((a, b) => rule === 'FEFO' ? a.expires.localeCompare(b.expires) : a.arrived.localeCompare(b.arrived)); const picks = []; for (const b of order) { if (qty === 0) break; const take = Math.min(b.qty, qty); if (take > 0) { picks.push({ id: b.id, take }); b.qty -= take; qty -= take; } } if (qty > 0) throw new Error('short by ' + qty); return picks; } ISO dates (YYYY-MM-DD) sort correctly as strings, so no date parsing is needed for the comparison.
The difference on real numbers
const stock = () => [ { id: 'A', qty: 60, arrived: '2026-11-02', expires: '2026-12-20' }, { id: 'B', qty: 40, arrived: '2026-11-10', expires: '2026-12-08' }, ]; allocate(stock(), 50, 'FIFO'); // [{ id: 'A', take: 50 }] -> all of B expires on 8 Dec allocate(stock(), 50, 'FEFO'); // [{ id: 'B', take: 40 }, { id: 'A', take: 10 }] What a production version adds
- a tie-breaker when two batches share an expiry date (arrival date, then batch id), so the result is repeatable;
- a minimum remaining life per customer, so a batch with two days left is not sent to a customer who needs ten;
- blocked batches skipped entirely;
- the allocation stored with each shipment, so a recall can be traced back.
We use the same rule in Expiry, Batch & Recall Control (paid, with a free demo).
