-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
116 lines (100 loc) · 2.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* @typedef Polarity
* Info.
* @property {number} polarity
* Calculated polarity of input.
* @property {number} positivity
* Total positivity.
* @property {number} negativity
* Total negativity.
* @property {Array<string>} positive
* All positive words.
* @property {Array<string>} negative
* All negative words.
*
* @typedef {Record<string, number>} Inject
* Values to inject.
*/
import {afinn165} from 'afinn-165'
import {emojiEmotion} from 'emoji-emotion'
/** @type {Inject} */
export const polarities = {}
const own = {}.hasOwnProperty
/** @type {Inject} */
const emoji = {}
let index = 0
while (++index < emojiEmotion.length) {
const info = emojiEmotion[index]
polarities[info.emoji] = info.polarity
polarities[':' + info.name + ':'] = info.polarity
}
inject(afinn165)
inject(emoji)
/**
* Get a polarity result from given values, optionally with one time injections.
*
* @param {Array<string>} values
* @param {Inject} [inject]
* @returns {Polarity}
*/
export function polarity(values, inject) {
const words = values || []
let index = words.length === 0 ? 1 : words.length
let positivity = 0
let negativity = 0
/** @type {Array<string>} */
const positive = []
/** @type {Array<string>} */
const negative = []
while (index--) {
const value = words[index]
const weight = getPolarity(value, inject)
if (!weight) {
continue
}
if (weight > 0) {
positive.push(value)
positivity += weight
} else {
negative.push(value)
negativity += weight
}
}
return {
polarity: positivity + negativity,
positivity,
negativity,
positive,
negative
}
}
/**
* Inject values on the `polarities` object.
*
* @param {Inject} values
*/
export function inject(values) {
/** @type {string} */
let value
for (value in values) {
if (own.call(values, value)) {
polarities[value] = values[value]
}
}
}
/**
* Get the polarity of a word.
*
* @param {string} value
* @param {Inject} [inject]
* @returns {number}
*/
function getPolarity(value, inject) {
if (own.call(polarities, value)) {
return polarities[value]
}
if (inject && own.call(inject, value)) {
return inject[value]
}
return 0
}