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