-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum.js
50 lines (38 loc) · 1.34 KB
/
sum.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
module.exports = function(RED) {
"use strict";
function sum(config) {
RED.nodes.createNode(this, config);
var node = this;
this.topic = config.topic;
this.topics = {};
this.on("input", function(msg) {
if( msg.hasOwnProperty("payload") ) {
var input = Number(msg.payload);
// handle reset
if( msg.hasOwnProperty("reset") && msg.reset ) {
node.topics = {};
msg.payload = 0;
node.send(msg);
}
// handle input
else if( !isNaN(input) && isFinite(input) ) {
node.topics[msg.topic.toString()] = input;
var sum = Object.keys(node.topics).reduce(function(a, b) {
return a + node.topics[b];
}, 0);
msg.payload = sum;
// overwrite topic if configured
if( node.topic ) {
msg.topic = node.topic;
}
node.send(msg);
}
// everything else
else {
node.log("Not a number: " + msg.payload);
}
}
});
}
RED.nodes.registerType("sum", sum);
};