0

I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.

I give an example of a code as I could do it.

// I use underscore in NodeJS

_.each(refresh, (value, key) => {

    if(key === 'station') {

        station.add({ id: value });

    } else if(key === 'concentrator') {

        concentrator.add({ id: value });
        
    } else if....
});

It is possible to run the function according to your string to avoid so much checking with IF, etc.

[key].add({ id: value });

I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.

Thanks !

Anto
  • 313
  • 1
  • 3
  • 13

1 Answers1

1

Creating an anonymous function on an object is the best approach. As you can use the key to call the method.

Here is an example in code pen: https://codepen.io/liam-hamblin/pen/KKyapNP

The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.

const operations = {};

operations.add = (obj) => {
  document.write("add - ");
  document.write(JSON.stringify(obj));
}

operations.subtract = (obj) => {
  document.write("subtract - ");
  document.write(JSON.stringify(obj));
}

const input = prompt("Enter Function Name, type either subtract or add");

if (operations[input]) {
  operations[input]({id:1});
} else {
  document.write("no matching method")
}
  • It is different functionality. You use methods called from string and I need to run the add method from a string. – Anto Feb 07 '22 at 19:03