]>
Commit | Line | Data |
---|---|---|
1 | 'use strict'; | |
2 | ||
3 | ||
4 | var Promise = require('bluebird'); | |
5 | var cheerio = require('cheerio'); | |
6 | require('neon'); | |
7 | var request = require('request'); | |
8 | ||
9 | ||
10 | var Conjugator = Class({}, "Conjugator")({ | |
11 | prototype : { | |
12 | _baseUrl: "http://www.spanishdict.com/conjugate/", | |
13 | _selector: ".aa .neoConj tr td", | |
14 | ||
15 | init : function init(config) { | |
16 | config = config || {}; | |
17 | ||
18 | Object.keys(config).forEach(function (property) { | |
19 | this[property] = config[property]; | |
20 | }, this); | |
21 | }, | |
22 | ||
23 | conjugate : function conjugate(verb) { | |
24 | return new Promise(function (resolve, reject) { | |
25 | request(this._baseUrl + verb, function (err, res, body) { | |
26 | var $, result, finalVerb ; | |
27 | if (err) { | |
28 | return reject(err); | |
29 | } | |
30 | $ = cheerio.load(body); | |
31 | result = $('.vtable-word')[10]; | |
32 | ||
33 | if (!result) { | |
34 | console.log("Verb not found: ", verb); | |
35 | return reject(new Error("Not a valid verb")); | |
36 | } | |
37 | ||
38 | finalVerb = this._extractWord(result); | |
39 | ||
40 | console.log(verb, finalVerb); | |
41 | resolve(finalVerb); | |
42 | }.bind(this)); | |
43 | }.bind(this)); | |
44 | }, | |
45 | ||
46 | _extractWord : function _extractWord(node) { | |
47 | var word = "", components; | |
48 | ||
49 | node.children.forEach(function (child) { | |
50 | if (child.type === "text") { | |
51 | word += child.data; | |
52 | } else { | |
53 | word += this._extractWord(child); | |
54 | } | |
55 | }, this); | |
56 | ||
57 | word = word.split(",")[0]; // multiple conjugations, take 1 | |
58 | components = word.split(" "); // some special cases have two words | |
59 | // use the last, why not | |
60 | ||
61 | return components[components.length - 1]; | |
62 | } | |
63 | } | |
64 | }); | |
65 | ||
66 | module.exports = Conjugator; |