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);
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);
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);
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);
@Teemu explained how to do it without branching, and there are times where that can be beneficial (example: Why is processing a sorted array faster than processing an unsorted array?).
function hello(x) {
console.log(['greater', 'smaller'][+(x < 0)]);
}
hello(1);
hello(-1);
but by definition you cannot achieve behavior based on a condition without a conditional.