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 !
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")
}
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,
There are 4 records in my database
I've a M:N(many-to-many) relationship between Invoice and Item entities and I'm using sequelize unmanaged transaction to create an invoice by adding items in it
I'm facing an issue, the goal I want to achieve is call a function from a webpack file