add: iterator to log parser methods
This commit is contained in:
@ -7,6 +7,8 @@
|
|||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
import "sort"
|
||||||
|
|
||||||
// report aggregates the final report
|
// report aggregates the final report
|
||||||
type report struct {
|
type report struct {
|
||||||
sum map[string]result // metrics per domain
|
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.total = r.total.add(parsed.result)
|
||||||
r.sum[domain] = parsed.add(r.sum[domain])
|
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 (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// summarize prints the report and errors if any
|
// summarize prints the report and errors if any
|
||||||
func summarize(r *report, errs ...error) {
|
func summarize(r *report, errs ...error) {
|
||||||
sort.Strings(r.domains)
|
|
||||||
|
|
||||||
fmt.Printf("%-30s %10s\n", "DOMAIN", "VISITS")
|
fmt.Printf("%-30s %10s\n", "DOMAIN", "VISITS")
|
||||||
fmt.Println(strings.Repeat("-", 45))
|
fmt.Println(strings.Repeat("-", 45))
|
||||||
|
|
||||||
for _, domain := range r.domains {
|
next, cur := r.iterator()
|
||||||
parsed := r.sum[domain]
|
for next() {
|
||||||
fmt.Printf("%-30s %10d\n", domain, parsed.visits)
|
rec := cur()
|
||||||
|
fmt.Printf("%-30s %10d\n", rec.domain, rec.visits)
|
||||||
}
|
}
|
||||||
fmt.Printf("\n%-30s %10d\n", "TOTAL", r.total.visits)
|
fmt.Printf("\n%-30s %10d\n", "TOTAL", r.total.visits)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user