How to convert this function without using if/else?
function Menu() {
if (!currentUser || currentUser.getValue == 7) {
return false
} else {
return true
}
}
CodePudding user response:
Maybe just do ?
function validateMenu() {
return p.currentUser && p.currentUser.getValue('id') !== 7
}
I really don't understand why would you want to use a callback or a Promise for this case. There is nothing asynchronous involved, only two simple conditions being checked.
You might want to read a bit more about callbacks and Promises.
CodePudding user response:
It's
let showMenu = (!p.currentUser || p.currentUser.getValue('id') === 7) ? false : true;
If you want to use promises you can
function validateMenu() {
return new Promises((resolve, reject) => {
if (!p.currentUser || p.currentUser.getValue('id') === 7) {
resolve(false)
} else {
resolve(true)
}
});
}
CodePudding user response:
In function, like this
function validateMenu() {
return !(!p.currentUser || p.currentUser.getValue('id') === 7)
}
In variable, like below:
let showMenu = !(!p.currentUser || p.currentUser.getValue('id') === 7)
You don’t need to write return while declaring variables.
CodePudding user response:
why not pass the user to a function like this
const validateMenu = (user) => (!user || user.getValue('id') === 7) ? false : true;
then you can call validateMenu(p.currentUser)
CodePudding user response:
You don't need if...else
statement or conditional (ternary) operator, you could just use arrow function expression and logical operators:
const Menu = () => !!currentUser && currentUser.getValue('id') !== 7;
CodePudding user response:
You can do it using the Optional chaining (?.) operator, as shown below:
function isValueSeven(val) {
return !!(val?.getValue() === 7);
}
console.log(isValueSeven({ getValue: () => 7 }));
console.log(isValueSeven({ getValue: () => 8 }));
console.log(isValueSeven(null));