-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go2
116 lines (90 loc) · 2.3 KB
/
main.go2
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type Post struct {
ID string `json:"id"`
Index int `json:"index"`
IsActive bool `json:"isActive"`
IsVerified bool `json:"isVerified"`
User User `json:"user"`
Email string `json:"email"`
Level string `json:"level"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
Greeting string `json:"greeting"`
Favoritefruit string `json:"favoriteFruit"`
}
type User struct {
Points int `json:"points"`
Name Name `json:"name"`
Friends []Friend `json:"friends"`
Company string `json:"company"`
}
type Name struct {
First string `json:"first"`
Last string `json:"last"`
}
type Friend struct {
ID string `json:"id"`
Name string `json:"name"`
}
type UserLevelPoints struct {
FirstName string
LastName string
Level string
Points int
FriendCount int
}
func getPosts(filename string) ([]Post, error) {
var posts []Post
jsonFile, err := os.Open(filename)
defer jsonFile.Close()
if err != nil {
return nil, err
}
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, err
}
json.Unmarshal(byteValue, &posts)
return posts, nil
}
func getTopUsers(posts []Post) []UserLevelPoints {
postsByLevel := map[string]Post{}
userLevelPoints := make([]UserLevelPoints, 0)
for _, post := range posts {
// Set post for group when group does not already exist
if _, ok := postsByLevel[post.Level]; !ok {
postsByLevel[post.Level] = post
continue
}
// Replace post for group if points are higher for current post
if postsByLevel[post.Level].User.Points < post.User.Points {
postsByLevel[post.Level] = post
}
}
// Summarize user from post
for _, post := range postsByLevel {
userLevelPoints = append(userLevelPoints, UserLevelPoints{
FirstName: post.User.Name.First,
LastName: post.User.Name.Last,
Level: post.Level,
Points: post.User.Points,
FriendCount: len(post.User.Friends),
})
}
return userLevelPoints
}
func main() {
if posts, err := getPosts("/home/ani/repositories/pneumatic/examples/data.json"); posts != nil {
topUsers := getTopUsers(posts)
fmt.Printf("%+v\n", topUsers)
} else {
fmt.Printf("%+v\n", err)
}
fmt.Printf("hello, world\n")
}