diff options
| author | Ben Beltran <ben@nsovocal.com> | 2020-04-18 14:20:53 +0200 |
|---|---|---|
| committer | Ben Beltran <ben@nsovocal.com> | 2020-04-18 14:20:53 +0200 |
| commit | da393520c4a1b33bffdfe26974e817f2c65267d3 (patch) | |
| tree | 1c7b0999dbf235ee54b864167baefbd0422a3331 /lib | |
| parent | e865f21be5685ef2fbc57e36460f8d6819e0fe34 (diff) | |
Update code for 2020
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/Conjugator.js | 86 | ||||
| -rw-r--r-- | lib/InsultGenerator.js | 211 |
2 files changed, 109 insertions, 188 deletions
diff --git a/lib/Conjugator.js b/lib/Conjugator.js index 78dd713..c4e74f7 100644 --- a/lib/Conjugator.js +++ b/lib/Conjugator.js @@ -1,66 +1,54 @@ 'use strict'; +const Cheerio = require('cheerio'); +const Fetch = require('node-fetch'); -var Promise = require('bluebird'); -var cheerio = require('cheerio'); -require('neon'); -var request = require('request'); +const internals = { + kBaseUrl: 'http://www.spanishdict.com/conjugate/', + kSelector: 'table .ex-tip', + kThirdPersonPresentPosition: 10, + extractWord(node) { -var Conjugator = Class({}, "Conjugator")({ - prototype : { - _baseUrl: "http://www.spanishdict.com/conjugate/", - _selector: "table .ex-tip", + let word = ''; - init : function init(config) { - config = config || {}; + node.children.forEach(function (child) { - Object.keys(config).forEach(function (property) { - this[property] = config[property]; - }, this); - }, + if (child.type === 'text') { + word += child.data; + } else { + word += internals.extractWord(child); + } + }); - conjugate : function conjugate(verb) { - return new Promise(function (resolve, reject) { - request(this._baseUrl + verb, function (err, res, body) { - var $, result, finalVerb ; - if (err) { - return reject(err); - } - $ = cheerio.load(body); - result = $(this._selector)[10]; + word = word.split(',')[0]; // multiple conjugations, take 1 - if (!result) { - console.log("Verb not found: ", verb); - return reject(new Error("Not a valid verb")); - } + const components = word.split(' '); // some special cases have two words + // use the last, why not - finalVerb = this._extractWord(result); + return components[components.length - 1]; + } +}; - console.log(verb, finalVerb); - resolve(finalVerb); - }.bind(this)); - }.bind(this)); - }, +module.exports = { + async conjugate(verb) { - _extractWord : function _extractWord(node) { - var word = "", components; + console.debug(`Conjugating ${verb}`); - node.children.forEach(function (child) { - if (child.type === "text") { - word += child.data; - } else { - word += this._extractWord(child); - } - }, this); + const response = await Fetch(internals.kBaseUrl + verb); + const body = await response.text(); - word = word.split(",")[0]; // multiple conjugations, take 1 - components = word.split(" "); // some special cases have two words - // use the last, why not + const $ = Cheerio.load(body); + const result = $(internals.kSelector)[internals.kThirdPersonPresentPosition]; - return components[components.length - 1]; + if (!result) { + console.error('Verb not found: ', verb); + throw new Error('Not a valid verb'); } - } -}); -module.exports = Conjugator; + const plainTextVerb = internals.extractWord(result); + console.debug(verb, plainTextVerb); + + return plainTextVerb; + } +}; diff --git a/lib/InsultGenerator.js b/lib/InsultGenerator.js index 5c40651..af9408b 100644 --- a/lib/InsultGenerator.js +++ b/lib/InsultGenerator.js @@ -1,180 +1,113 @@ 'use strict'; +const Fs = require('fs'); +const Path = require('path'); -var fs = require('fs'); +const Conjugator = require('./Conjugator'); -var Promise = require('bluebird'); -require('neon'); +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+?([^ ]+)/, -var Conjugator = require('./Conjugator'); + wordList: null, -var InsultGenerator = Class({}, "InsultGenerator")({ - prototype : { - file : null, - verbs: null, - nouns: null, + // Gets the list of words, key can be either nouns or verbs - _maxTries: 10, - _loaded: false, - _verbRe: /^[0-9]+\-v\s+?lemma\s+?([^ ]+)/, - _nounRe: /^[0-9]+\-n\s+?lemma\s+?([^ ]+)/, - _conjugator: null, + async getWordList(key) { - init : function init(config) { - config = config || {}; + internals.wordList = internals.wordList || await internals.readWordFile(); + return internals.wordList[key]; + }, - Object.keys(config).forEach(function (property) { - this[property] = config[property]; - }, this); + // Read the list of words and returns it - this._conjugator = new Conjugator(); - }, + readWordFile() { - generate : function generate(config) { - var selectedVerb; - return this._load() - .then(function () { - return this._getVerb(); - }.bind(this)).then(function (verb) { - return this._conjugateVerb(verb); - }.bind(this)).then(function (conjugatedVerb) { - selectedVerb = conjugatedVerb; - return this._getNoun(); - }.bind(this)).then(function (noun) { - return this._generateInsult(selectedVerb, noun); - }.bind(this)); - }, + return new Promise(function (resolve, reject) { - _load : function _load() { - return this._loadFile() - .then(function () { - return this._loadVerbs(); - }.bind(this)).then(function () { - return this._loadNouns(); - }.bind(this)); - }, + console.debug('Reading word file'); + Fs.readFile(internals.kWordFile, {encoding: 'utf8'}, function (err, contents) { - _loadFile : function _loadFile() { - return new Promise(function (resolve, reject) { - if (this._loaded) { - return resolve(); + if (err) { + return reject(err); } - fs.readFile(this.file, {encoding: 'utf8'}, function (err, contents) { - if (err) { - return reject(err); - } + const verbs = new Set(); + const nouns = new Set(); + const words = contents.split('\n'); - this._contents = contents; - this._loaded = true; - resolve(); - }.bind(this)); - }.bind(this)); - }, + console.debug(`Found ${words.length} words, categorizing`); - _loadVerbs : function _loadVerbs() { - return new Promise(function (resolve, reject) { - if (this.verbs) { - return resolve(); - } + words.forEach(function (line) { - this.verbs = []; - this._contents.split('\n').forEach(function (line) { - var matches; - matches = line.match(this._verbRe); + const matches = line.match(internals.kWordRe); if (matches) { - if (this.verbs.indexOf(matches[1]) === -1) { - this.verbs.push(matches[1]) + if (matches[1] === 'v') { + return verbs.add(matches[2]); } + + nouns.add(matches[2]); } - }, this); + }); - resolve(); - }.bind(this)); - }, + console.debug(`Nouns: ${nouns.size}, Verbs: ${verbs.size}`); - _loadNouns : function _loadNouns() { - return new Promise(function (resolve, reject) { - if (this.nouns) { - return resolve(); - } + resolve({ + verbs: [...verbs], + nouns: [...nouns] + }); + }); + }); + }, - this.nouns = []; - this._contents.split('\n').forEach(function (line) { - var matches; - matches = line.match(this._nounRe); + // Gets a conjugated verb - if (matches) { - if (this.nouns.indexOf(matches[1]) === -1) { - this.nouns.push(matches[1]) - } - } - }, this); + async getVerb() { - resolve(); - }.bind(this)); - }, + const verbs = await internals.getWordList('verbs'); + const verb = verbs[Math.floor(Math.random()*verbs.length)]; + return await Conjugator.conjugate(verb); + }, - _getVerb : function _getVerb() { - var index; - index = Math.floor(Math.random()*this.verbs.length); - return Promise.resolve(this.verbs[index]); - }, + // Gets a pluralized noun - _conjugateVerb : function _conjugateVerb(verb) { - return new Promise(function (resolve, reject) { - var tries; + async getNoun() { - tries = 0; + const nouns = await internals.getWordList('nouns'); + const noun = nouns[Math.floor(Math.random()*nouns.length)]; + return internals.pluralize(noun); + }, - var attemptConjugation = function attemptConjugation(verb, tries) { - if (tries > this._maxTries) { - return reject(new Error("Couldn't find a proper verb")); - }; + // Pluralizes a word - this._conjugator.conjugate(verb) - .then(function (conjugatedVerb) { - resolve(conjugatedVerb); - }) - .catch(function (err) { - this._getVerb().then(function (verb) { - attemptConjugation.bind(this)(verb, tries + 1); - }.bind(this)) - }.bind(this)); - }; + pluralize(noun) { - setTimeout(attemptConjugation.bind(this, verb, 0), 0); - }.bind(this)); - }, + const lastLetter = noun[noun.length - 1]; - _getNoun : function _getNoun() { - var index, noun; - index = Math.floor(Math.random()*this.nouns.length); - return Promise.resolve(this.nouns[index].toLowerCase()); - }, + if (lastLetter === 's') { + return noun; + } + + if (internals.kVowels.indexOf(lastLetter) >= 0) { + return noun + 's' + } - _generateInsult : function _generateInsult(verb, noun) { - return Promise.resolve(verb + this._pluralize(noun)); - }, + return noun + 'es'; + } +}; - // Super dumb pluralizer - _pluralize : function _pluralize(noun) { - var lastLetter; +module.exports = { - lastLetter = noun[noun.length - 1]; + // Generates an insult. - if (lastLetter === "s") { - return noun; - } + async generate() { - if (["a","e","i","o","u"].indexOf(lastLetter) >= 0) { - return noun + "s" - } + const verb = await internals.getVerb(); + const noun = await internals.getNoun(); - return noun + "es"; - } + return (verb + noun).toLowerCase(); } -}); - -module.exports = InsultGenerator; +}; |