Skip to content

Commit

Permalink
modified omikuji map to slice
Browse files Browse the repository at this point in the history
  • Loading branch information
isuzuki committed Aug 16, 2019
1 parent bc3d9dd commit fb7952e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 33 deletions.
10 changes: 1 addition & 9 deletions kadai4/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")

omikuji := omikuji.Omikuji{time.Now()}
ret, err := omikuji.Do()
res := Response{}

if err != nil {
res.Msg = err.Error()
log.Println("Error:", err)
} else {
res.Msg = ret
}
res := Response{omikuji.Do()}

if err := json.NewEncoder(w).Encode(res); err != nil {
log.Println("Error:", err)
Expand Down
33 changes: 11 additions & 22 deletions kadai4/omikuji/omikuji.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
package omikuji

import (
"fmt"
"math/rand"
"time"
)

var omikuji = map[int]string{
0: "凶",
1: "末吉",
2: "小吉",
3: "中吉",
4: "吉",
5: "大吉",
var omikuji = []string{
"凶",
"末吉",
"小吉",
"中吉",
"吉",
"大吉",
}

type Omikuji struct {
Expand All @@ -27,25 +26,15 @@ type OmikujiError struct {
Msg string
}

func (err *OmikujiError) Error() string {
return fmt.Sprintf(err.Msg)
}

func (o *Omikuji) Do() (string, error) {
func (o *Omikuji) Do() string {
var i int

_, m, d := o.Time.Date()
// 1/1 ~ 1/3のみ大吉を出す
if int(m) == 1 && d >= 1 && d <= 3 {
i = 5
} else {
i = rand.Intn(len(omikuji))
}

s, ok := omikuji[i]
if !ok {
return "", &OmikujiError{"おみくじが引けませんでした。"}
return "大吉"
}

return s, nil
i = rand.Intn(len(omikuji))
return omikuji[i]
}
4 changes: 2 additions & 2 deletions kadai4/omikuji/omikuji_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ func Test_NormalTime(t *testing.T) {
time := time.Date(2019, time.Month(8), 16, 0, 0, 0, 0, time.Local)
omikuji := omikuji.Omikuji{time}
expect := "大吉"
actual, _ := omikuji.Do()
actual := omikuji.Do()
if expect != actual {
t.Errorf(`Omikuji error: expect="%s" actual="%s"`, expect, actual)
}
Expand All @@ -28,7 +28,7 @@ func Test_SpecificPeriod(t *testing.T) {
for _, d := range days {
time := time.Date(2019, time.Month(m), d, 0, 0, 0, 0, time.Local)
omikuji := omikuji.Omikuji{time}
actual, _ := omikuji.Do()
actual := omikuji.Do()
if expect != actual {
t.Errorf(`Omikuji error: expect="%s" actual="%s"`, expect, actual)
}
Expand Down

0 comments on commit fb7952e

Please sign in to comment.