Drill

ProblemsJavaScript › orders

Total a basket that came off a queue

easyordersJavaScript

Order lines arrive from a message queue and the payload is not always clean: a line can be missing entirely, and quantities have been seen at zero.

orderTotal(lines: list<Line?>) → int

Solve it in the editor →

Where you start

function orderTotal(lines) {
  
}

Worked examples

CallResult
orderTotal([{"sku":"A","qty":2,"unitPrice":100},{"sku":"B","qty":3,"unitPrice":50}])350
orderTotal([{"sku":"A","qty":1,"unitPrice":10},null,{"sku":"C","qty":2,"unitPrice":5}])20
orderTotal([{"sku":"A","qty":0,"unitPrice":999},{"sku":"B","qty":-1,"unitPrice":999}])0
orderTotal([])0

Hint

Guard inside the loop, not before it. One bad line should not cost you the rest.

Reference solution in JavaScript
function orderTotal(lines) {
  let total = 0;
  for (const l of lines) {
    if (l === null || l.qty <= 0) continue;
    total += l.qty * l.unitPrice;
  }
  return total;
}

The same problem in another language

More orders problems in JavaScript