UNPKG

2.03 kBJavaScriptView Raw
1var afinn = require('../build/build.json');
2var tokenize = require('./tokenize');
3
4/**
5 * These words "flip" the sentiment of the following word.
6 */
7var 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 * Performs sentiment analysis on the provided input 'phrase'.
24 *
25 * @param {String} Input phrase
26 * @param {Object} Optional sentiment additions to AFINN (hash k/v pairs)
27 *
28 * @return {Object}
29 */
30module.exports = function (phrase, inject, callback) {
31 // Parse arguments
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 // Merge
38 if (inject !== null) {
39 afinn = Object.assign(afinn, inject);
40 }
41
42 // Storage objects
43 var tokens = tokenize(phrase),
44 score = 0,
45 words = [],
46 positive = [],
47 negative = [];
48
49 // Iterate over tokens
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 // Check for negation
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 // Handle optional async interface
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};