X-Git-Url: https://git.r.bdr.sh/rbdr/generador-de-insultos/blobdiff_plain/da393520c4a1b33bffdfe26974e817f2c65267d3..c0d27c055055f4aada0a96b779e0bd661347160c:/lib/InsultGenerator.js diff --git a/lib/InsultGenerator.js b/lib/InsultGenerator.js deleted file mode 100644 index af9408b..0000000 --- a/lib/InsultGenerator.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -const Fs = require('fs'); -const Path = require('path'); - -const Conjugator = require('./Conjugator'); - -const internals = { - kMaxAttempts: 10, - kVowels: ['a', 'e', 'i', 'o', 'u'], - kWordFile: Path.resolve(__dirname, '../ext/words.tab'), - kWordRe: /^[0-9]+\-(n|v)\s+?lemma\s+?([^ ]+)/, - - wordList: null, - - // Gets the list of words, key can be either nouns or verbs - - async getWordList(key) { - - internals.wordList = internals.wordList || await internals.readWordFile(); - return internals.wordList[key]; - }, - - // Read the list of words and returns it - - readWordFile() { - - return new Promise(function (resolve, reject) { - - console.debug('Reading word file'); - Fs.readFile(internals.kWordFile, {encoding: 'utf8'}, function (err, contents) { - - if (err) { - return reject(err); - } - - const verbs = new Set(); - const nouns = new Set(); - const words = contents.split('\n'); - - console.debug(`Found ${words.length} words, categorizing`); - - words.forEach(function (line) { - - const matches = line.match(internals.kWordRe); - - if (matches) { - if (matches[1] === 'v') { - return verbs.add(matches[2]); - } - - nouns.add(matches[2]); - } - }); - - console.debug(`Nouns: ${nouns.size}, Verbs: ${verbs.size}`); - - resolve({ - verbs: [...verbs], - nouns: [...nouns] - }); - }); - }); - }, - - // Gets a conjugated verb - - async getVerb() { - - const verbs = await internals.getWordList('verbs'); - const verb = verbs[Math.floor(Math.random()*verbs.length)]; - return await Conjugator.conjugate(verb); - }, - - // Gets a pluralized noun - - async getNoun() { - - const nouns = await internals.getWordList('nouns'); - const noun = nouns[Math.floor(Math.random()*nouns.length)]; - return internals.pluralize(noun); - }, - - // Pluralizes a word - - pluralize(noun) { - - const lastLetter = noun[noun.length - 1]; - - if (lastLetter === 's') { - return noun; - } - - if (internals.kVowels.indexOf(lastLetter) >= 0) { - return noun + 's' - } - - return noun + 'es'; - } -}; - -module.exports = { - - // Generates an insult. - - async generate() { - - const verb = await internals.getVerb(); - const noun = await internals.getNoun(); - - return (verb + noun).toLowerCase(); - } -};