-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquizService.go
105 lines (72 loc) · 2.04 KB
/
quizService.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
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
package main
import (
"errors"
"fmt"
)
type QuizService struct {
QuestionsRepo *QuestionsRepo
UserAnswersRepo *UserAnswersRepo
}
func (q *QuizService) Init() {
q.QuestionsRepo = &QuestionsRepo{}
q.QuestionsRepo.Init()
q.UserAnswersRepo = &UserAnswersRepo{}
}
func (q *QuizService) GetQuestions() (map[int]*Question, error) {
return q.QuestionsRepo.GetQuestions()
}
func (q *QuizService) InsertAnswers(container *UserAnswerContainer) error {
questions, err := q.QuestionsRepo.GetQuestions()
if err != nil {
return err
}
correctAnswers := 0
for questionID, optionLabel := range container.Answers {
question, questionFound := questions[questionID]
if !questionFound {
return errors.New("questionId not found")
}
option, optionFound := question.Options[optionLabel]
if !optionFound {
return errors.New("option not found")
}
if option.Correct {
correctAnswers++
}
}
userAnswersResultContainer := &UserAnswerResultContainer{
UserID: container.UserID,
CorrectAnswers: correctAnswers,
}
return q.UserAnswersRepo.InsertUserAnswerResults(userAnswersResultContainer)
}
func (q *QuizService) GetUserReport(userID int) (*UserReport, error) {
container, err := q.UserAnswersRepo.GetUserAnswerResults(userID)
if err != nil {
return nil, err
}
totalUser := q.UserAnswersRepo.GetTotalUsers()
lessPerformantUsers := getLessPerformantUsersTotal(userID, container.CorrectAnswers)
floatTotal := float64(totalUser)
floatLess := float64(lessPerformantUsers)
userRatio := floatLess * float64(100) / floatTotal
percentage := fmt.Sprintf("%f%%", userRatio)
userReport := &UserReport{
UserID: userID,
CorrectAnswers: container.CorrectAnswers,
Percentage: percentage,
}
return userReport, nil
}
func getLessPerformantUsersTotal(userID int, correctAnswers int) int {
worstResults := 0
for uID, container := range containerList {
if uID == userID {
continue //we don't calculate the same user
}
if container.CorrectAnswers < correctAnswers {
worstResults++
}
}
return worstResults
}