generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
66 lines (56 loc) · 1.2 KB
/
stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package hw10programoptimization
import (
"encoding/json"
"fmt"
"io"
"regexp"
"strings"
)
type User struct {
ID int
Name string
Username string
Email string
Phone string
Password string
Address string
}
type DomainStat map[string]int
func GetDomainStat(r io.Reader, domain string) (DomainStat, error) {
u, err := getUsers(r)
if err != nil {
return nil, fmt.Errorf("get users error: %w", err)
}
return countDomains(u, domain)
}
type users [100_000]User
func getUsers(r io.Reader) (result users, err error) {
content, err := io.ReadAll(r)
if err != nil {
return
}
lines := strings.Split(string(content), "\n")
for i, line := range lines {
var user User
if err = json.Unmarshal([]byte(line), &user); err != nil {
return
}
result[i] = user
}
return
}
func countDomains(u users, domain string) (DomainStat, error) {
result := make(DomainStat)
for _, user := range u {
matched, err := regexp.Match("\\."+domain, []byte(user.Email))
if err != nil {
return nil, err
}
if matched {
num := result[strings.ToLower(strings.SplitN(user.Email, "@", 2)[1])]
num++
result[strings.ToLower(strings.SplitN(user.Email, "@", 2)[1])] = num
}
}
return result, nil
}