diff options
author | Michaël Ball <michael.ball@gmail.com> | 2016-09-08 17:20:54 +0100 |
---|---|---|
committer | Michaël Ball <michael.ball@gmail.com> | 2016-09-08 17:23:48 +0100 |
commit | ed0b45cfce6d54924002ef005795f3c45b808dac (patch) | |
tree | 20e1c92264b4cbd8a6f368bd388f02aa9bce35b7 /generator | |
parent | f7340d2ccda6aeda51ca9a6c134496b314358922 (diff) |
Move generation to library
Diffstat (limited to 'generator')
-rw-r--r-- | generator/generator.go | 45 | ||||
-rw-r--r-- | generator/generator_test.go | 15 |
2 files changed, 60 insertions, 0 deletions
diff --git a/generator/generator.go b/generator/generator.go new file mode 100644 index 0000000..3ec5154 --- /dev/null +++ b/generator/generator.go @@ -0,0 +1,45 @@ +package generator + +import ( + "bufio" + "math/rand" + "os" + "time" +) + +func readLines(path string) ([]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var lines []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + return lines, scanner.Err() +} + +// RandomWords picks numberOfWords random words from the file located at +// wordsFile +func RandomWords(wordsFile string, numberOfWords int) ([]string, error) { + rand.Seed(time.Now().UTC().UnixNano()) + + words, err := readLines(wordsFile) + + if err != nil { + return nil, err + } + + phraseWords := make([]string, numberOfWords) + + for index := 0; index < numberOfWords; index++ { + randInt := rand.Intn((len(words) - 1)) + + phraseWords[index] = words[randInt] + } + + return phraseWords, nil +} diff --git a/generator/generator_test.go b/generator/generator_test.go new file mode 100644 index 0000000..4cda593 --- /dev/null +++ b/generator/generator_test.go @@ -0,0 +1,15 @@ +package generator + +import "testing" + +func TestRandomWords(t *testing.T) { + words, err := RandomWords("/usr/share/dict/words", 4) + + if err != nil { + t.Errorf("%s", err) + } + + if len(words) != 4 { + t.Errorf("RandomWords does not return the correct number of words") + } +} |