Sunday, June 10, 2018

Injecting random numbers, undefined or null

The inject node is very handy but, at the time of this writing, it lacks the capability to inject some kind of values.

This is what the node is capable of injecting in a flow:



What if you want to inject a random integer number, or the undefined value or the null value?

You can´t. It will be necessary to an additional function node. So I did.

This is the code inside the function node:

const MIN = 1;
const MAX = 99;
//The maximum is exclusive and the minimum is inclusive
switch (msg.payload) {

case "undefined" :
msg.payload = undefined;
break;

case "null" :
msg.payload = null;
break;

case "random" :
msg.payload =function getRandomInt(min = MIN, max = MAX) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}();
break;
}
return msg;


It requires that the minimum and maximum values of random numbers be hardcoded in the first line of the function.

The undefined and null values that will be passed in the  msg.payload will be really undefined and null, not strings.



Here a screenshot of the debug panel after pressing a few times the inject nodes.




Here the flow:


[{"id":"52e18ccb.c4d624","type":"inject","z":"391a528.22394ae","name":"","topic":"","payload":"random","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":229.0999984741211,"y":155.00000190734863,"wires":[["26b163fc.3928ec"]]},{"id":"26b163fc.3928ec","type":"function","z":"391a528.22394ae","name":"random, undefined, null","func":"const MIN = 1;\nconst MAX = 99;\n//The maximum is exclusive and the minimum is inclusive\n \nswitch (msg.payload) {\n\ncase \"undefined\" :\nmsg.payload = undefined;\nbreak;\n\ncase \"null\" :\nmsg.payload = null;\nbreak;\n\ncase  \"random\" :\nmsg.payload =function getRandomInt(min = MIN, max = MAX) {\n  min = Math.ceil(min);\n  max = Math.floor(max);\n  return Math.floor(Math.random() * (max - min)) + min;\n}();\nbreak;\n}\nreturn msg;\n\n","outputs":1,"noerr":0,"x":421.1000747680664,"y":154.00000190734863,"wires":[["325c68cb.b409a8"]]},{"id":"325c68cb.b409a8","type":"debug","z":"391a528.22394ae","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":632.1000595092773,"y":154.00000190734863,"wires":[]},{"id":"ae52d302.9a904","type":"inject","z":"391a528.22394ae","name":"","topic":"","payload":"null","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":228,"y":205,"wires":[["26b163fc.3928ec"]]},{"id":"b7d139ff.0bec58","type":"inject","z":"391a528.22394ae","name":"","topic":"","payload":"undefined","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":221,"y":105.00000095367432,"wires":[["26b163fc.3928ec"]]}]