]> git.r.bdr.sh - rbdr/generador-de-insultos/blob - lib/InsultGenerator.js
af9408b8a2c1e6b791ba258ca2880bdc4b59ec92
[rbdr/generador-de-insultos] / lib / InsultGenerator.js
1 'use strict';
2
3 const Fs = require('fs');
4 const Path = require('path');
5
6 const Conjugator = require('./Conjugator');
7
8 const internals = {
9 kMaxAttempts: 10,
10 kVowels: ['a', 'e', 'i', 'o', 'u'],
11 kWordFile: Path.resolve(__dirname, '../ext/words.tab'),
12 kWordRe: /^[0-9]+\-(n|v)\s+?lemma\s+?([^ ]+)/,
13
14 wordList: null,
15
16 // Gets the list of words, key can be either nouns or verbs
17
18 async getWordList(key) {
19
20 internals.wordList = internals.wordList || await internals.readWordFile();
21 return internals.wordList[key];
22 },
23
24 // Read the list of words and returns it
25
26 readWordFile() {
27
28 return new Promise(function (resolve, reject) {
29
30 console.debug('Reading word file');
31 Fs.readFile(internals.kWordFile, {encoding: 'utf8'}, function (err, contents) {
32
33 if (err) {
34 return reject(err);
35 }
36
37 const verbs = new Set();
38 const nouns = new Set();
39 const words = contents.split('\n');
40
41 console.debug(`Found ${words.length} words, categorizing`);
42
43 words.forEach(function (line) {
44
45 const matches = line.match(internals.kWordRe);
46
47 if (matches) {
48 if (matches[1] === 'v') {
49 return verbs.add(matches[2]);
50 }
51
52 nouns.add(matches[2]);
53 }
54 });
55
56 console.debug(`Nouns: ${nouns.size}, Verbs: ${verbs.size}`);
57
58 resolve({
59 verbs: [...verbs],
60 nouns: [...nouns]
61 });
62 });
63 });
64 },
65
66 // Gets a conjugated verb
67
68 async getVerb() {
69
70 const verbs = await internals.getWordList('verbs');
71 const verb = verbs[Math.floor(Math.random()*verbs.length)];
72 return await Conjugator.conjugate(verb);
73 },
74
75 // Gets a pluralized noun
76
77 async getNoun() {
78
79 const nouns = await internals.getWordList('nouns');
80 const noun = nouns[Math.floor(Math.random()*nouns.length)];
81 return internals.pluralize(noun);
82 },
83
84 // Pluralizes a word
85
86 pluralize(noun) {
87
88 const lastLetter = noun[noun.length - 1];
89
90 if (lastLetter === 's') {
91 return noun;
92 }
93
94 if (internals.kVowels.indexOf(lastLetter) >= 0) {
95 return noun + 's'
96 }
97
98 return noun + 'es';
99 }
100 };
101
102 module.exports = {
103
104 // Generates an insult.
105
106 async generate() {
107
108 const verb = await internals.getVerb();
109 const noun = await internals.getNoun();
110
111 return (verb + noun).toLowerCase();
112 }
113 };