UNPKG

1.76 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 assign = require('lodash.assign');
12
13var afinn = require('../build/AFINN.json');
14var tokenize = require('./tokenize');
15
16/**
17 * Performs sentiment analysis on the provided input 'phrase'.
18 *
19 * @param {String} Input phrase
20 * @param {Object} Optional sentiment additions to AFINN (hash k/v pairs)
21 *
22 * @return {Object}
23 */
24module.exports = function (phrase, inject, callback) {
25 // Parse arguments
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 // Merge
32 if (inject !== null) {
33 afinn = assign(afinn, inject);
34 }
35
36 // Storage objects
37 var tokens = tokenize(phrase),
38 score = 0,
39 words = [],
40 positive = [],
41 negative = [];
42
43 // Iterate over tokens
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 // Handle optional async interface
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};