Kodewick
Start learning →
Basic←→0 / 70

Not on the menu

#061BasicErrorsMaps4 min

The noodle bar's Price(dish) looks up a price and returns an error for a dish that isn't on the menu. Fill in the spot in Bill(order): on an error, add 1 to missing and skip that dish. It returns the total and how many dishes were missing.

Examples
Bill([]string{"noodles", "soup"})→(40, 0)
Bill([]string{"noodles", "pizza"})→(28, 1)
The functionfunc Bill(order []string) (int, int)
main.go
package main

import "errors"

var menu = map[string]int{"noodles": 28, "dumplings": 20, "soup": 12}

func Price(dish string) (int, error) {
	p, ok := menu[dish]
	if !ok {
		return 0, errors.New("not on the menu")
	}
	return p, nil
}

func Bill(order []string) (int, int) {
	total, missing := 0, 0
	for _, dish := range order {
		p, err := Price(dish)
		if err != nil {
			// your code here: add 1 to missing and skip this dish
		}
		total += p
	}
	return total, missing
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.