skip to Main Content

I had a problem in ‘code wars‘ website and I couldn’t solve this Kata because I can’t use if statement or shortcut way, the kata said :

you have a function that has two argument and they are two numbers (a, b)if a > b return ‘a greater than b’ I need your help guys, thank you for everything.

I tried for three times, although I couldn’t find the solutions.

3

Answers


  1. If you cannot use neither an explicit if statement nor a ternary operator, you can use an object as dictionary for the various cases, like:

    function compare(a, b) {
        return ({
            '-1': 'a lesser than b',
            0: 'a equals b',
            1: 'a greater than b'
        })[Math.sign(a - b)];
    }
    
    compare(4, 2) // returns 'a greater than b'
    compare(3, 3) // returns 'a equals b'
    compare(3, 5) // returns 'a lesser than b'
    
    Login or Signup to reply.
  2. One way to do this is by using a ternary operator, which is a concise way to write conditional statements. possible solution,

    function compareNumbers(a, b) {
      return a > b ? 'a greater than b': 'a less than b'
    }
    
    console.log(compareNumbers(4,2));
    
    Login or Signup to reply.
  3. How about this way ?

    function compare(a, b) {
        return `${Math.max(a, b)} is greater than ${Math.min(a, b)}`;
    }
    
    console.log(compare(2, 4)) // '4 is greater than 2'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search