1 | var afinn = require('../build/build.json');
|
2 | var tokenize = require('./tokenize');
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | var negators = {
|
8 | 'cant': 1,
|
9 | 'can\'t': 1,
|
10 | 'dont': 1,
|
11 | 'don\'t': 1,
|
12 | 'doesnt': 1,
|
13 | 'doesn\'t': 1,
|
14 | 'not': 1,
|
15 | 'non': 1,
|
16 | 'wont': 1,
|
17 | 'won\'t': 1,
|
18 | 'isnt': 1,
|
19 | 'isn\'t': 1
|
20 | };
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | module.exports = function (phrase, inject, callback) {
|
31 |
|
32 | if (typeof phrase === 'undefined') phrase = '';
|
33 | if (typeof inject === 'undefined') inject = null;
|
34 | if (typeof inject === 'function') callback = inject;
|
35 | if (typeof callback === 'undefined') callback = null;
|
36 |
|
37 |
|
38 | if (inject !== null) {
|
39 | afinn = Object.assign(afinn, inject);
|
40 | }
|
41 |
|
42 |
|
43 | var tokens = tokenize(phrase),
|
44 | score = 0,
|
45 | words = [],
|
46 | positive = [],
|
47 | negative = [];
|
48 |
|
49 |
|
50 | var len = tokens.length;
|
51 | while (len--) {
|
52 | var obj = tokens[len];
|
53 | var item = afinn[obj];
|
54 | if (!afinn.hasOwnProperty(obj)) continue;
|
55 |
|
56 |
|
57 | if (len > 0) {
|
58 | var prevtoken = tokens[len-1];
|
59 | if (negators[prevtoken]) item = -item;
|
60 | }
|
61 |
|
62 | words.push(obj);
|
63 | if (item > 0) positive.push(obj);
|
64 | if (item < 0) negative.push(obj);
|
65 |
|
66 | score += item;
|
67 | }
|
68 |
|
69 |
|
70 | var result = {
|
71 | score: score,
|
72 | comparative: tokens.length > 0 ? score / tokens.length : 0,
|
73 | tokens: tokens,
|
74 | words: words,
|
75 | positive: positive,
|
76 | negative: negative
|
77 | };
|
78 |
|
79 | if (callback === null) return result;
|
80 | process.nextTick(function () {
|
81 | callback(null, result);
|
82 | });
|
83 | };
|