UNPKG

1.73 kBJavaScriptView Raw
1/**
2 * AFINN-based sentiment analysis for Node.js
3 *
4 * @package sentiment
5 * @author Andrew Sliwinski <andrewsliwinski@acm.org>
6 */
7
8/**
9 * Dependencies
10 */
11var afinn = require('../build/AFINN.json');
12var tokenize = require('./tokenize');
13
14/**
15 * Performs sentiment analysis on the provided input 'phrase'.
16 *
17 * @param {String} Input phrase
18 * @param {Object} Optional sentiment additions to AFINN (hash k/v pairs)
19 *
20 * @return {Object}
21 */
22module.exports = function (phrase, inject, callback) {
23 // Parse arguments
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 // Merge
30 if (inject !== null) {
31 afinn = Object.assign(afinn, inject);
32 }
33
34 // Storage objects
35 var tokens = tokenize(phrase),
36 score = 0,
37 words = [],
38 positive = [],
39 negative = [];
40
41 // Iterate over tokens
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 // Handle optional async interface
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};