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 3b71ebb
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 37 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
37 changes: 11 additions & 26 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 @@ -23,29 +22,15 @@ func (o *Omikuji) SetSeed(seed int64) {
rand.Seed(seed)
}

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 3b71ebb

Please sign in to comment.