init
This commit is contained in:
commit
7a6b109e78
4 changed files with 164 additions and 0 deletions
53
internal/counter/counter.go
Normal file
53
internal/counter/counter.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package counter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
const maxLineSize = 1024 * 1024
|
||||
|
||||
type Result struct {
|
||||
Name string
|
||||
Count int
|
||||
}
|
||||
|
||||
func Count(r io.Reader) (map[string]int, error) {
|
||||
counts := make(map[string]int)
|
||||
|
||||
scanner := bufio.NewScanner(r)
|
||||
scanner.Buffer(make([]byte, 64*1024), maxLineSize)
|
||||
|
||||
for scanner.Scan() {
|
||||
name := scanner.Text()
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
counts[name]++
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func Sorted(counts map[string]int) []Result {
|
||||
results := make([]Result, 0, len(counts))
|
||||
for name, count := range counts {
|
||||
results = append(results, Result{Name: name, Count: count})
|
||||
}
|
||||
|
||||
sort.Slice(results, func(i, j int) bool {
|
||||
if results[i].Count != results[j].Count {
|
||||
return results[i].Count > results[j].Count
|
||||
}
|
||||
|
||||
return results[i].Name < results[j].Name
|
||||
})
|
||||
|
||||
return results
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue