The below function works good by if statements , I want the same functionality by using without condition statements.
Hello(x){
If(x<0){
Console.log("greater");
}Else{
Console.log("smaller");
}
};
Hello(1);
Hello(-1);
CodePudding user response:
You could use an Object but it's odd. An if...else statement or it's shorter ternary form more clearly conveys the logic at play which is always preferable.
function Hello(x) {
const lt = {
true: "smaller",
false: "greater"
};
console.log(lt[x < 0]);
};
Hello(1);
Hello(-1);
CodePudding user response:
This is probably a stupid thing to actually do and might be overly specific to your example but...:
const hello = (x) => {
const lt = x < 0;
console.log("greater".repeat(lt) "smaller".repeat(1 - lt));
};
hello(-1);
hello(1);
Borrowing from @Teemu's comment a slightly more flexible thing could be:
const if_else = (cond_fn, if_fn, else_fn = (x) => x) =>
[else_fn, if_fn][ cond_fn()]();
const hello = (x) =>
if_else(
() => x < 0,
() => console.log('greater'),
() => console.log('smaller')
);
hello(-1);
hello(1);