Converted to a Go app
This commit is contained in:
parent
543c1790de
commit
d4b3322077
28 changed files with 302 additions and 1 deletions
58
models/question.go
Normal file
58
models/question.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math/rand"
|
||||
|
||||
"lmika.dev/pkg/modash/moslice"
|
||||
)
|
||||
|
||||
type QuestionSet struct {
|
||||
Questions []Question
|
||||
}
|
||||
|
||||
type Choice struct {
|
||||
Text string
|
||||
IsRight bool
|
||||
}
|
||||
|
||||
type Question struct {
|
||||
Text string
|
||||
Choices []Choice
|
||||
Fact string
|
||||
}
|
||||
|
||||
func (q Question) Render() (RenderedQuestion, error) {
|
||||
choices := moslice.MapIndex(q.Choices, func(c Choice, i int) RenderedChoice {
|
||||
return RenderedChoice{
|
||||
ID: i + 1,
|
||||
Text: c.Text,
|
||||
}
|
||||
})
|
||||
rand.Shuffle(len(choices), func(i, j int) {
|
||||
choices[i], choices[j] = choices[j], choices[i]
|
||||
})
|
||||
_, idx, ok := moslice.FindWithIndexWhere(q.Choices, func(c Choice) bool { return c.IsRight })
|
||||
if !ok {
|
||||
return RenderedQuestion{}, errors.New("question does not have a right answer")
|
||||
}
|
||||
|
||||
return RenderedQuestion{
|
||||
Question: q.Text,
|
||||
Fact: q.Fact,
|
||||
Choices: choices,
|
||||
RightChoice: idx + 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type RenderedChoice struct {
|
||||
ID int
|
||||
Text string
|
||||
}
|
||||
|
||||
type RenderedQuestion struct {
|
||||
Question string
|
||||
Fact string
|
||||
Choices []RenderedChoice
|
||||
RightChoice int
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue