1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | var afinn = require('../build/AFINN.json');
|
12 | var tokenize = require('./tokenize');
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | module.exports = function (phrase, inject, callback) {
|
23 |
|
24 | if (typeof phrase === 'undefined') phrase = '';
|
25 | if (typeof inject === 'undefined') inject = null;
|
26 | if (typeof inject === 'function') callback = inject;
|
27 | if (typeof callback === 'undefined') callback = null;
|
28 |
|
29 |
|
30 | if (inject !== null) {
|
31 | afinn = Object.assign(afinn, inject);
|
32 | }
|
33 |
|
34 |
|
35 | var tokens = tokenize(phrase),
|
36 | score = 0,
|
37 | words = [],
|
38 | positive = [],
|
39 | negative = [];
|
40 |
|
41 |
|
42 | var len = tokens.length;
|
43 | while (len--) {
|
44 | var obj = tokens[len];
|
45 | var item = afinn[obj];
|
46 | if (!afinn.hasOwnProperty(obj)) continue;
|
47 |
|
48 | words.push(obj);
|
49 | if (item > 0) positive.push(obj);
|
50 | if (item < 0) negative.push(obj);
|
51 |
|
52 | score += item;
|
53 | }
|
54 |
|
55 |
|
56 | var result = {
|
57 | score: score,
|
58 | comparative: score / tokens.length,
|
59 | tokens: tokens,
|
60 | words: words,
|
61 | positive: positive,
|
62 | negative: negative
|
63 | };
|
64 |
|
65 | if (callback === null) return result;
|
66 | process.nextTick(function () {
|
67 | callback(null, result);
|
68 | });
|
69 | };
|