Search code examples
javascriptarraysnode-red

Can this code be shorter and easier to implement?


Im making one script for node red and i want to make it simple to implement. How can i compress this code even more?

var notDetected = "NOT DETECTED";
var models = [
    context.get('model1')||notDetected,
    context.get('model2')||notDetected,
    context.get('model3')||notDetected,
    context.get('model4')||notDetected
];
switch(msg.topic)
{
    case "core_1":
        models[0] = msg.model + "";
        context.set('model1', models[0]);
        break;
    case "core_2":
        models[1] = msg.model + "";
        context.set('model2', models[1]);
        break;
    case "core_3":
        models[2] = msg.model + "";
        context.set('model3', models[2]);
        break;
    case "core_4":
        models[3] = msg.model + "";
        context.set('model4', models[3]);
        break;
}
var msgs = [
    {payload: models[0]},
    {payload: models[1]},
    {payload: models[2]},
    {payload: models[3]}
];
return msgs;

Can models be compressed even more? What about msgs? Can i remove that id inside for models to match msgs id, for example

msg[x] = {payload: models[x]};

Is it possible?


Solution

  • Compressing the code in terms of readability/extensibility (not necessarily space):

    • You can use a loop to fill the models and msgs array,
    • You can split the core_X string at the first "_" to get the index, but this might cause security issues if you don't validate the input; or you can use a map from the four strings core_1 to the actual number.

    Take a look here for the for loop: https://www.w3schools.com/js/js_loop_for.asp

    It could look like this:

    var msgs = [];
    for (x = 0; x < 4; x++) { 
        msgs[x] = {payload: models[x]};
    }