Problems › JavaScript › orders
Total a basket that came off a queue
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.
- A missing line contributes nothing and must not stop the sum.
- A line with a quantity of zero or less contributes nothing either.
- The total is in minor units.
orderTotal(lines: list<Line?>) → int
Where you start
function orderTotal(lines) {
}
Worked examples
| Call | Result |
|---|---|
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;
}