Drill

ProblemsJavaScript › inventory

Pick an order off the shelves

mediuminventoryJavaScript

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.

pickFromShelves(wanted: int, shelves: list<Shelf>) → list<Pick>

Solve it in the editor →

Where you start

function pickFromShelves(wanted, shelves) {
  
}

Worked examples

CallResult
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 JavaScript
function pickFromShelves(wanted, shelves) {
  const out = [];
  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;
}

The same problem in another language

More inventory problems in JavaScript