[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / core_nodes / logic / 16-range.js
1 /**
2  * Copyright 2013 IBM Corp.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  **/
16
17 module.exports = function(RED) {
18     "use strict";
19     function RangeNode(n) {
20         RED.nodes.createNode(this, n);
21         this.action = n.action;
22         this.round = n.round || false;
23         this.minin = Number(n.minin);
24         this.maxin = Number(n.maxin);
25         this.minout = Number(n.minout);
26         this.maxout = Number(n.maxout);
27         var node = this;
28
29         this.on('input', function (msg) {
30             var n = Number(msg.payload);
31             if (!isNaN(n)) {
32                 if (node.action == "clamp") {
33                     if (n < node.minin) { n = node.minin; }
34                     if (n > node.maxin) { n = node.maxin; }
35                 }
36                 if (node.action == "roll") {
37                     if (n >= node.maxin) { n = (n - node.minin) % (node.maxin - node.minin) + node.minin; }
38                     if (n <  node.minin) { n = (n - node.minin) % (node.maxin - node.minin) + node.maxin; }
39                 }
40                 msg.payload = ((n - node.minin) / (node.maxin - node.minin) * (node.maxout - node.minout)) + node.minout;
41                 if (node.round) { msg.payload = Math.round(msg.payload); }
42                 node.send(msg);
43             }
44             else { node.log("Not a number: "+msg.payload); }
45         });
46     }
47     RED.nodes.registerType("range", RangeNode);
48 }