Drill

ProblemsGo › orders

Total a basket that came off a queue

easyordersArraysMathGo

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

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func orderTotal(lines []*Line) int {
	
}

Worked examples

CallResult
orderTotal([]*Line{&Line{Sku: "A", Qty: 2, UnitPrice: 100}, &Line{Sku: "B", Qty: 3, UnitPrice: 50}})350
orderTotal([]*Line{&Line{Sku: "A", Qty: 1, UnitPrice: 10}, nil, &Line{Sku: "C", Qty: 2, UnitPrice: 5}})20
orderTotal([]*Line{&Line{Sku: "A", Qty: 0, UnitPrice: 999}, &Line{Sku: "B", Qty: -1, UnitPrice: 999}})0
orderTotal([]*Line{})0

Hint

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

Reference solution in Go
func orderTotal(lines []*Line) int {
	total := 0
	for _, l := range lines {
		if l == nil || l.Qty <= 0 {
			continue
		}
		total += l.Qty * l.UnitPrice
	}
	return total
}

The same problem in another language

More orders problems in Go