-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);
juzraai
  • 5,693
  • 8
  • 33
  • 47
Harikrishnan k
  • 203
  • 2
  • 8

3 Answers3

0

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);
pilchard
  • 12,414
  • 5
  • 11
  • 23
0

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);
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8
  • lol. I think you can safely take 'probably' out of that sentence ;) – pilchard Mar 29 '22 at 09:51
  • @pilchard I part remember seeing a video once by someone who was explaining that removing conditionals can speed up code by eliminating the need for branch prediction or something like that. (This was compiled code hmmm ... possibly assembly actually (I didn't understand much of it)). Anyway, this was with numbers, and based on a true or false result part of the equation was multiplied by 0 or 1 thus not requiring branch prediction. This was the first idea I came up with for strings. :) – Ben Stephens Mar 29 '22 at 09:57
  • Don't get me wrong, I'm amused by solution. Also it's not that far off my object suggestion so we're in the same boat. – pilchard Mar 29 '22 at 10:03
0

@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.

anthonynorton
  • 1,173
  • 10
  • 19