From c5e844ccb62d72e9b29956570146dc3cbdc3c079 Mon Sep 17 00:00:00 2001 From: Inanc Gumus Date: Fri, 26 Apr 2019 10:11:52 +0300 Subject: [PATCH] add: iterator to log parser methods --- .../xxx-log-parser-methods/report.go | 25 +++++++++++++++++++ .../xxx-log-parser-methods/summarize.go | 10 +++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/x-tba/2-methods/xxx-log-parser-methods/report.go b/x-tba/2-methods/xxx-log-parser-methods/report.go index ee3de75..7f9200e 100644 --- a/x-tba/2-methods/xxx-log-parser-methods/report.go +++ b/x-tba/2-methods/xxx-log-parser-methods/report.go @@ -7,6 +7,8 @@ package main +import "sort" + // report aggregates the final report type report struct { sum map[string]result // metrics per domain @@ -37,3 +39,26 @@ func (r *report) update(parsed parserResult) { r.total = r.total.add(parsed.result) r.sum[domain] = parsed.add(r.sum[domain]) } + +// iterator returns `next()` to detect when the iteration ends, +// and a `cur()` to return the current result. +// iterator iterates sorted by domains. +func (r *report) iterator() (next func() bool, cur func() result) { + sort.Strings(r.domains) + + // remember the last iterated result + var last int + + next = func() bool { + defer func() { last++ }() + return len(r.domains) > last + } + + cur = func() result { + // returns a copy so the caller cannot change it + name := r.domains[last-1] + return r.sum[name] + } + + return +} diff --git a/x-tba/2-methods/xxx-log-parser-methods/summarize.go b/x-tba/2-methods/xxx-log-parser-methods/summarize.go index 4fbf125..07e8ab5 100644 --- a/x-tba/2-methods/xxx-log-parser-methods/summarize.go +++ b/x-tba/2-methods/xxx-log-parser-methods/summarize.go @@ -9,20 +9,18 @@ package main import ( "fmt" - "sort" "strings" ) // summarize prints the report and errors if any func summarize(r *report, errs ...error) { - sort.Strings(r.domains) - fmt.Printf("%-30s %10s\n", "DOMAIN", "VISITS") fmt.Println(strings.Repeat("-", 45)) - for _, domain := range r.domains { - parsed := r.sum[domain] - fmt.Printf("%-30s %10d\n", domain, parsed.visits) + next, cur := r.iterator() + for next() { + rec := cur() + fmt.Printf("%-30s %10d\n", rec.domain, rec.visits) } fmt.Printf("\n%-30s %10d\n", "TOTAL", r.total.visits)