summaryrefslogtreecommitdiff
path: root/generator/generator.go
blob: 3ec5154f09c23489f94a83a327fb33475a231d93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
}