add: iterator to log parser methods
This commit is contained in:
@ -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
|
||||
}
|
||||
|
@ -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)
|
||||
|
||||
|
Reference in New Issue
Block a user