-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
265 lines (243 loc) · 7.47 KB
/
helpers.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
const chalk = require('chalk');
const logger = require('./logger');
const inquirer = require('inquirer');
const { getDefinitions, getExamples, getRelatedWords, getRandomWord } = require('./services');
const parseRelatedWordsResponse = (data) => {
let result = { antonym: [], synonym: [] };
if (data && data.length) {
result = data.reduce((acc, v) => {
acc[v.relationshipType] = v.words;
return acc;
}, result);
return result;
}
return result;
};
const parseDefinitionsResponse = (data) => {
if (data && data.length) {
return data.filter((d) => d.text).map((d) => d.text);
}
return [];
};
const parseExamplesResponse = (data) => {
if (data && data.examples && data.examples.length) {
return data.examples.map((e) => e.text);
}
return [];
};
const parseAllResponses = (responses) => {
const [definitionsRes, examplesRes, relatedWordsRes] = responses;
const relatedWords = parseRelatedWordsResponse(relatedWordsRes);
return {
definitions: parseDefinitionsResponse(definitionsRes),
synonyms: relatedWords.synonym,
antonyms: relatedWords.antonym,
examples: parseExamplesResponse(examplesRes),
};
};
exports.displayData = async (displayFn, params) => {
try {
if (params) {
if (Array.isArray(params)) {
await displayFn(...params);
} else {
await displayFn(params);
}
} else {
await displayFn();
}
} catch (err) {
if (err.message) {
logger.error(err.message);
} else {
logger.error(err);
}
logger.info('\n');
}
};
exports.displayDef = async (word, definitions) => {
try {
const result = definitions || (await getDefinitions(word));
if (result && result.length > 0) {
logger.info('Definitions');
result
.filter((defs) => defs.text)
.forEach((defs) => {
logger.success(defs.text);
});
logger.info('\n');
} else {
throw new Error();
}
} catch (error) {
throw new Error(`No definitions for ${word}`);
}
};
exports.displaySyn = async (word, relatedWords) => {
try {
const result = relatedWords || (await getRelatedWords(word, 'synonym'));
if (result && result.length > 0) {
logger.info('Synonyms');
result[0].words.forEach((synonym) => {
logger.success(synonym);
});
logger.info('\n');
} else {
throw new Error();
}
} catch (error) {
throw new Error(`No synonyms for ${word}`);
}
};
exports.displayAnt = async (word, relatedWords) => {
try {
const result = relatedWords || (await getRelatedWords(word, 'antonym'));
if (result && result.length > 0) {
logger.info('Antonyms');
result[0].words.forEach((antonym) => {
logger.success(antonym);
});
logger.info('\n');
} else {
throw new Error();
}
} catch (error) {
throw new Error(`No antonyms for ${word}`);
}
};
exports.displayEx = async (word, examples) => {
try {
const result = examples || (await getExamples(word));
if (result && result.examples && result.examples.length > 0) {
logger.info('Examples');
result.examples.forEach((e) => {
logger.success(e.text);
});
logger.info('\n');
} else {
throw new Error();
}
} catch (error) {
throw new Error(`No examples for ${word}`);
}
};
exports.displayAll = async (word) => {
const [definitions, examples, relatedWords] = await Promise.allSettled([
getDefinitions(word, 5),
getExamples(word),
getRelatedWords(word, 'synonym,antonym'),
]);
if (definitions.status === 'fulfilled') {
this.displayData(this.displayDef, [word, definitions.value]);
}
if (examples.status === 'fulfilled') {
this.displayData(this.displayEx, [word, examples.value]);
}
if (relatedWords.status === 'fulfilled') {
// filter out antonyms
this.displayData(this.displayAnt, [word, relatedWords.value.filter((rw) => rw.relationshipType === 'antonym')]);
// filter out synonyms
this.displayData(this.displaySyn, [word, relatedWords.value.filter((rw) => rw.relationshipType === 'synonym')]);
}
};
exports.displayWordOfDay = async () => {
const result = await getRandomWord();
logger.info('Word Of The Day');
logger.info(chalk.bold.greenBright(result.word.toUpperCase()));
logger.info('\n');
await this.displayAll(result.word);
};
// jumble the given word
const jumbleWord = (word) => {
const jumbledWordArr = word.split('');
for (var i = jumbledWordArr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = jumbledWordArr[i];
jumbledWordArr[i] = jumbledWordArr[j];
jumbledWordArr[j] = temp;
}
const jumbledWord = jumbledWordArr.join('');
if (jumbledWord === word) {
return jumbleWord(word);
}
return jumbledWord;
};
// display a random question from the plethora of information
const getRandomQuestion = (word, wordInfo, isHint = false) => {
const availableChoices = isHint ? ['jumble'] : [];
for (let k in wordInfo) {
if (wordInfo[k] && wordInfo[k].length && k !== 'examples') {
availableChoices.push(k);
}
}
const randomChoice = Math.floor(availableChoices.length * Math.random());
let question;
switch (availableChoices[randomChoice]) {
case 'definitions':
question = `Definition: ${wordInfo.definitions.shift()}`;
break;
case 'synonyms':
question = `Synonym: ${wordInfo.synonyms.shift()}`;
break;
case 'antonyms':
question = `Antonym: ${wordInfo.antonyms.shift()}`;
break;
case 'jumble':
question = `Jumble: ${jumbleWord(word)}`;
break;
}
return question;
};
// action to perform if the answer is wrong
const wrongAnswerAction = async (word, wordInfo) => {
const answer = await inquirer.prompt([
{
type: 'list',
name: 'selection',
message: 'What do you want to do?',
choices: [
{ name: '1: Try again', value: 1 },
{ name: '2: Hint', value: 2 },
{ name: '3: Quit', value: 3 },
],
},
]);
switch (answer.selection) {
case 1:
await askQuestion(word, wordInfo, 'Try Again');
break;
case 2:
await askQuestion(word, wordInfo, 'HINT- ' + getRandomQuestion(word, wordInfo, true));
break;
case 3:
logger.info('Correct Answer');
logger.info(chalk.bold.greenBright(word.toUpperCase()));
logger.info('\n');
await this.displayAll(word);
break;
}
};
// ask the question and perform action based on the answer
const askQuestion = async (word, wordInfo, promptMessage) => {
const question = promptMessage || getRandomQuestion(word, wordInfo);
const answers = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Guess the word. ' + question }]);
if (checkAnswer(answers.answer, word, wordInfo.synonyms)) {
logger.success('Correct');
} else {
logger.success('Wrong Answer!');
wrongAnswerAction(word, wordInfo);
}
};
// match the answer entered with the word and synonyms of word
const checkAnswer = (answer, word, synonymsLeft) => {
const answerLowerCase = answer && answer.toLowerCase();
return answerLowerCase === word || synonymsLeft.indexOf(answerLowerCase) > -1;
};
exports.displayGame = async () => {
const { word } = await getRandomWord();
const apiResponses = await Promise.all([getDefinitions(word), getExamples(word), getRelatedWords(word)]);
const wordInfo = parseAllResponses(apiResponses);
logger.info(`Welcome to Game-A-Dict. Let's play`);
logger.info('Please guess the word from the information.\n');
askQuestion(word, wordInfo);
};