-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-lib.js
71 lines (60 loc) · 1.62 KB
/
server-lib.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
/* eslint-env node */
const path = require('path');
const fs = require('fs');
const wordPath = path.join(__dirname, 'data/words.txt');
const imgPath = path.join(__dirname, 'public/img');
let readWords;
let wordArray;
let imgArray;
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
const greetings = shuffleArray([
'hello', 'welcome', 'hi', 'hello', 'welcome', 'question:'
]);
const goodbye = shuffleArray([
'goodbye', 'the end', 'fin', 'thank you', 'thanks', 'thank you.'
]);
const lib = {
getGreeting() {
return this.capFirst(greetings[Math.floor(Math.random() * greetings.length)]);
},
getGoodbye() {
return this.capFirst(goodbye[Math.floor(Math.random() * goodbye.length)]);
},
getImg() {
if (imgArray.length === 0) {
imgArray = this.initImages();
}
return imgArray.pop();
},
getWord() {
if (wordArray.length === 0) {
wordArray = this.initWords();
}
return this.capFirst(wordArray.pop());
},
initWords: () => shuffleArray(readWords).slice(0),
initImages: () => shuffleArray(fs.readdirSync(imgPath)),
capFirst: str => str.split(' ')
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join(' ')
};
fs.readFile(wordPath, 'utf8', (err, wordTxt) => {
if (err) {
console.error(err.stack); // eslint-disable-line no-console
}
else {
readWords = wordTxt.split('\n').filter(s => s.match(/[a-z]/i));
wordArray = lib.initWords();
}
});
imgArray = lib.initImages();
module.exports = lib;