Problems › TypeScript › inventory
Pick an order off the shelves
A picker needs a quantity of one part, and it is spread across several shelves. Walk the shelves in the order given and take what you can from each until the order is filled.
- Take as much as a shelf holds, but never more than is still needed.
- Skip shelves that would contribute nothing.
- If the shelves cannot cover it, take everything they have and stop there.
- A request of zero or less picks nothing.
pickFromShelves(wanted: int, shelves: list<Shelf>) → list<Pick>
Where you start
function pickFromShelves(wanted: number, shelves: Shelf[]): Pick[] {
}
Worked examples
| Call | Result |
|---|---|
pickFromShelves(12, [{"code":"A1","available":5},{"code":"A2","available":0},{"code":"B3","available":20}]) | [{"code":"A1","taken":5},{"code":"B3","taken":7}] |
pickFromShelves(4, [{"code":"A1","available":10}]) | [{"code":"A1","taken":4}] |
pickFromShelves(30, [{"code":"A1","available":5},{"code":"B3","available":6}]) | [{"code":"A1","taken":5},{"code":"B3","taken":6}] |
pickFromShelves(0, [{"code":"A1","available":5}]) | [] |
Hint
Carry a running "still needed" figure and stop as soon as it hits zero.
Reference solution in TypeScript
function pickFromShelves(wanted: number, shelves: Shelf[]): Pick[] {
const out: Pick[] = [];
let need = wanted;
for (const s of shelves) {
if (need <= 0) break;
const take = Math.min(need, s.available);
if (take <= 0) continue;
out.push({ code: s.code, taken: take });
need -= take;
}
return out;
}