Skip to content

Report Open Tasks and Download the Project

The Course
•
22 min study
Exercise

Count open tasks

Add a line after Tasks: in the report. Print Open: followed by the count of unfinished tasks. Keep any write error visible to the caller. Test an empty queue, the sample input, and a queue whose only task is done.

Your working space Go
package main import ( "fmt" "os" ) func main() { if err := run(os.Stdin, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } package main import ( "cmp" "errors" "fmt" "slices" "strings" ) type TaskID int32 type Task struct { ID TaskID Title string Done bool } type Queue struct { tasks map[TaskID]Task } var ( errID = errors.New("ID must be a positive 32-bit integer") errTitle = errors.New("title is required") errDuplicate = errors.New("ID already exists") errMissing = errors.New("task not found") errDone = errors.New("task is already done") ) func (q *Queue) Add(id TaskID, title string) error { if id <= 0 { return errID } title = strings.TrimSpace(title) if title == "" { return errTitle } if _, exists := q.tasks[id]; exists { return fmt.Errorf("task %d: %w", id, errDuplicate) } if q.tasks == nil { q.tasks = make(map[TaskID]Task) } q.tasks[id] = Task{ID: id, Title: title} return nil } func (q *Queue) Finish(id TaskID) error { task, exists := q.tasks[id] if !exists { return fmt.Errorf("task %d: %w", id, errMissing) } if task.Done { return fmt.Errorf("task %d: %w", id, errDone) } task.Done = true q.tasks[id] = task return nil } func (q *Queue) Tasks() []Task { tasks := make([]Task, 0, len(q.tasks)) for _, task := range q.tasks { tasks = append(tasks, task) } slices.SortFunc(tasks, func(a, b Task) int { return cmp.Compare(a.ID, b.ID) }) return tasks } package main import ( "bufio" "errors" "fmt" "io" "strconv" "strings" ) func parseID(text string) (TaskID, error) { n, err := strconv.ParseInt(text, 10, 32) if err != nil || n <= 0 { return 0, errID } return TaskID(n), nil } // execute distinguishes a command rejection from an output failure. func execute(q *Queue, w io.Writer, line string) (commandErr, writeErr error) { verb, rest, _ := strings.Cut(line, " ") rest = strings.TrimSpace(rest) switch verb { case "add": rawID, title, ok := strings.Cut(rest, " ") if !ok { return errors.New("use add ID title"), nil } id, err := parseID(rawID) if err != nil { return err, nil } if err := q.Add(id, title); err != nil { return err, nil } _, err = fmt.Fprintf(w, "Added %d\n", id) return nil, err case "done": id, err := parseID(rest) if err != nil { return err, nil } if err := q.Finish(id); err != nil { return err, nil } _, err = fmt.Fprintf(w, "Done %d\n", id) return nil, err case "list": if rest != "" { return errors.New("list takes no arguments"), nil } return nil, report(w, q.Tasks()) default: return fmt.Errorf("unknown command %q", verb), nil } } func report(w io.Writer, tasks []Task) error { if _, err := fmt.Fprintln(w, "Task queue"); err != nil { return err } for _, task := range tasks { status := "open" if task.Done { status = "done" } if _, err := fmt.Fprintf(w, "%d [%s] %s\n", task.ID, status, task.Title); err != nil { return err } } _, err := fmt.Fprintln(w, "Tasks:", len(tasks)) return err } func run(r io.Reader, w io.Writer) error { var queue Queue scanner := bufio.NewScanner(r) lineNumber := 0 for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if line == "" { continue } commandErr, writeErr := execute(&queue, w, line) if writeErr != nil { return fmt.Errorf("write line %d: %w", lineNumber, writeErr) } if commandErr != nil { if _, err := fmt.Fprintf(w, "Line %d: %s\n", lineNumber, commandErr); err != nil { return fmt.Errorf("write line %d: %w", lineNumber, err) } } } if err := scanner.Err(); err != nil { return fmt.Errorf("read input: %w", err) } return nil } add 9 Draft notes add 2 Read chapter two add 2 Replacement done 2 done 7 list
Hint 1: the idea

The report already receives the ordered snapshot. Count unfinished entries from that slice.

Hint 2: a first step

Check the Tasks: line's write error before writing another line.

Worked solution

Replace the last two lines in report with:

Go
if _, err := fmt.Fprintln(w, "Tasks:", len(tasks)); err != nil {
	return err
}
open := 0
for _, task := range tasks {
	if !task.Done {
		open++
	}
}
_, err := fmt.Fprintln(w, "Open:", open)
return err

The sample produces Open: 1. An empty or fully completed queue produces Open: 0. The browser playground has no checks.go, but the downloaded project does: "Try it locally" below shows how its test reacts to this change and where to update the expected transcript.

Try it locally

Download the original task queue. Extract it and run the following from the directory containing go.mod with Go 1.24 or newer.

Shell
go run . < sample.txt
go test .

The browser uses one main package with an alternate entry file for checks. Locally, the Go testing package calls the same check function through queue_test.go. That file is short enough to read in full:

Go
package main

import "testing"

func TestQueueContract(t *testing.T) {
	if err := checkQueue(); err != nil {
		t.Fatal(err)
	}
}
  • go test compiles every file in the folder, including those ending in _test.go, and runs each function whose name starts with Test and that takes a *testing.T.
  • checkQueue lives in checks.go. It is the same function the browser check runs. It builds queues, runs transcripts and returns the first broken rule as an error, or nil.
  • t.Fatal(err) marks the test as failed, prints the error and stops the test. If you tried the optional Go test section on Day 6, this is the same idea with one test instead of a table.

Run go test -v . to see the test by name:

Text
=== RUN   TestQueueContract
--- PASS: TestQueueContract (0.00s)
PASS

Now break a rule on purpose. In queue.go, change the duplicate check if _, exists := q.tasks[id]; exists { to if false { and run go test . again:

Text
--- FAIL: TestQueueContract (0.00s)
    queue_test.go:7: duplicate ID: got <nil>
FAIL

The message names the broken rule: adding a duplicate ID returned no error. Restore the line. If you keep the Open: change from the exercise above, go test fails in the same way until you update the expected transcript in checks.go.

Was this article helpful?

Your response is saved on this device.