I want to call a unique function according to the user's input on JavaScript. I'm working with Node.js, not HTML inputs. I'll leave an example code that explains my general code's goal. Is there any better approach than I did? What would you recommend to me? I don't want to add all the new functions to Map. I want to turn into dynamic too.
let functions = new Map([
["Annually", annually],
["Daily", daily],
["Weekly", weekly],
]);
async function choice() {
const answer = await inquirer.prompt({
name: "choice",
type: "list",
message: "How often do you want to get a notification?",
choices: ["Annually", "Daily", "Weekly"], //Gets choice from users think it's like a HTML form
});
functions.get(answer.choice)(); // Gets the function from map after that calls the function
}
async function annually() {
console.log("Annually works.");
}
async function weekly() {
console.log("Weekly works.");
}
async function daily() {
console.log("Daily works.");
}
CodePudding user response:
The way you are accomplishing this seems like it would work, but I think there is a better way to do this that is more readable.
function daily() {
console.log("Daily works.");
}
function weekly() {
console.log("Weekly works.");
}
function annually() {
console.log("Annually works.");
}
function evalInput(input) {
switch(input){
case "Daily":
daily();
break;
case "Weekly":
weekly();
break;
case "Annually":
annually();
break;
default:
//do something
}
}
async function getChoice(){
const answer = await inquirer.prompt({
name: "choice",
type: "list",
message: "How often do you want to get a notification?",
choices: ["Annually", "Daily", "Weekly"]
});
evalInput(answer.choice);
}
No need to store the functions in a map unless you really need to. I also removed the async
keyword from your functions that were not await
ing anything.
CodePudding user response:
If these functions are in global object's scope you can do this:
var fn = answer.choice.toString();
if (global[fn] === "function") {
global[fn]();
}
If its in a module and you know the module exports
var someExports = require('./someExportsFile.js');
Object.keys(someExports)[fn];
PS:
If this was in browser, you could have used
var brFn = window[fn)];
if (typeof brFn === "function") brFn();
CodePudding user response:
you can use eval.
async function choice() {
const answer = await inquirer.prompt({
name: 'choice',
type: 'list',
message: 'How often do you want to get a notification?',
choices: ['annually', 'daily', 'weekly'],
})
eval(answer.choice).call() // you can use eval
}
function annually() {
console.log('Annually works.')
}
function weekly() {
console.log('Weekly works.')
}
function daily() {
console.log('Daily works.')
}