From eaa1acf83a3650e5aefe4f117e5229f6323ae6a8 Mon Sep 17 00:00:00 2001 From: juggledad Date: Mon, 26 Oct 2020 04:00:57 -0400 Subject: [PATCH] Add option to dynamically pass in 'From' and 'To' - fixed bug when 'From' was greater than 'To' by flipping the two --- function/random/random.js | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/function/random/random.js b/function/random/random.js index dac7b0b9..6b2face1 100644 --- a/function/random/random.js +++ b/function/random/random.js @@ -3,13 +3,44 @@ module.exports = function(RED) { "use strict"; function RandomNode(n) { RED.nodes.createNode(this,n); - this.low = Number(n.low || 1); - this.high = Number(n.high || 10); + + this.low = Number(n.low) || ""; + this.high = Number(n.high) || ""; this.inte = n.inte || false; this.property = n.property||"payload"; var node = this; + + this.on("input", function(msg) { + + if (node.low === "") { + node.low = 1 + if ('from' in msg) { + if ( (typeof msg.from === 'number') + || ( (typeof msg.from === 'string') && (!isNaN(Number(msg.from)) ) )) { + node.low = Number(msg.from) + } + } + } + + if (node.high === "") { + node.high = 10 + if ('to' in msg) { + if ( (typeof msg.to === 'number') + || ( (typeof msg.to === 'string') && (!isNaN(Number(msg.to)) ) )) { + node.high = Number(msg.to) + } + } + } + + // flip the values if low > high var value; + if (node.low > node.high) { + value = node.low + node.low = node.high + node.high = value + } + if (node.inte == "true" || node.inte === true) { value = Math.round(Math.random() * (node.high - node.low + 1) + node.low - 0.5); }