Skip to content

Commit 2572f39

Browse files
author
en-ken
committed
feat: add typing core module.
1 parent 7b0fed7 commit 2572f39

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

kadai3/en-ken/typing/typing.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package typing
2+
3+
import (
4+
"math/rand"
5+
"time"
6+
)
7+
8+
// Typing is the class to judge input
9+
type Typing struct {
10+
dict []string
11+
nextText string
12+
}
13+
14+
// NewTyping is a constructor
15+
func NewTyping(textDict []string) *Typing {
16+
rand.Seed(time.Now().UnixNano())
17+
18+
return &Typing{
19+
dict: textDict,
20+
}
21+
}
22+
23+
// GetNextText returns next text
24+
func (t *Typing) GetNextText() string {
25+
i := rand.Int() % len(t.dict)
26+
t.nextText = t.dict[i]
27+
return t.nextText
28+
}
29+
30+
// IsCorrect judges if input is correct or not.
31+
func (t *Typing) IsCorrect(inputText string) bool {
32+
return t.nextText == inputText
33+
}

kadai3/en-ken/typing/typing_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package typing_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/gopherdojo/dojo6/kadai3/en-ken/typing"
7+
)
8+
9+
var dict = []string{"ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZ"}
10+
11+
func contains(s string) bool {
12+
for _, v := range dict {
13+
if v == s {
14+
return true
15+
}
16+
}
17+
return false
18+
}
19+
20+
func TestTypingCanGetNextText(t *testing.T) {
21+
typ := typing.NewTyping(dict)
22+
for i := 0; i < 100; i++ {
23+
txt := typ.GetNextText()
24+
if !contains(txt) {
25+
t.Errorf("actual: %v\n", txt)
26+
}
27+
}
28+
}
29+
30+
func TestTypingIsCorrect(t *testing.T) {
31+
typ := typing.NewTyping(dict)
32+
txt := typ.GetNextText()
33+
34+
if !typ.IsCorrect(txt) {
35+
t.Errorf("IsCorrect() must be true")
36+
}
37+
}
38+
39+
func TestTypingIsCorrectFailed(t *testing.T) {
40+
typ := typing.NewTyping(dict)
41+
typ.GetNextText()
42+
43+
if typ.IsCorrect("YZZ") {
44+
t.Errorf("IsCorrect() must be false")
45+
}
46+
}

0 commit comments

Comments
 (0)