-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
56 lines (46 loc) · 1.43 KB
/
index.js
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
46
47
48
49
50
51
52
53
54
55
56
function groupByFirstLetter(wordCollection) {
return wordCollection.reduce((result, word) => {
const firstLetter = word.charAt(0)
if (!(firstLetter in result)) {
result[firstLetter] = []
}
result[firstLetter].push(word)
return result
}, {})
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
function pickRandomly(wordCollection) {
return wordCollection[Math.floor(Math.random() * wordCollection.length)]
}
function findCommonLetters(lettersA, lettersB) {
return lettersA.reduce((result, letter) => {
if (lettersB.indexOf(letter) > -1) {
result.push(letter)
}
return result
}, [])
}
const animals = groupByFirstLetter(require('./animals.json'))
const adjectives = groupByFirstLetter(require('./adjectives.json'))
const possibleLetters = findCommonLetters(
Object.keys(adjectives),
Object.keys(animals)
)
function findRandomAdjective(letter) {
return pickRandomly(adjectives[letter])
}
function findRandomAnimalName(letter) {
return pickRandomly(animals[letter]).split(' ').join('-')
}
function generateRandomAnimalName() {
const letter = pickRandomly(possibleLetters)
const adjective = findRandomAdjective(letter)
const animal = findRandomAnimalName(letter)
return `${capitalizeFirstLetter(adjective)} ${animal}`
}
if (require.main === module) {
console.log(generateRandomAnimalName())
}
module.exports = generateRandomAnimalName