2

Suppose we have function, which returns 3 when passing 5 to it and return 5 when passing 3 to it. I know it is very easy with if else and switch.

for example

function countReturn(number){
  if(number === 3){
  return 5
 }

  if(number === 5){
  return 3
 }

}

But how can I implement the same logic without if else, switch or any built-in function?

Wahas Ali Mughal
  • 187
  • 2
  • 11

4 Answers4

2

You can store the return values in an array:

function countReturn(n) {
  let a = [,,,5,,3];
  return a[n];
}

That will return undefined for other inputs, just like your original code.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

You could take the sum (3 + 5) and return the delta of the actual number.

function threeOrFive(value) {
    return 8 - value;
}

console.log(threeOrFive(3)); // 5
console.log(threeOrFive(5)); // 3
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • `threeOrFive(1)` seems to return `7`, rather than OP's function which would return `undefined` in that case. Not sure what OP actually wants to happen with non-3 and non-5 values, though. – VLAZ Nov 05 '21 at 11:50
1

you can so it with ternary like this

return number === 3 ? 5 : (number === 5 ? 3 : 0);

Or you can do it with object

const obj = {
  "5": 3,
  "3": 5
};
return obj[number];
Thibaud
  • 1,059
  • 4
  • 14
  • 27
0

We can return the xored value between 5 and 3:

return number ^ 6

Implementing the same logic, it would return 3 when given 5 and vice versa

CodeCop
  • 1
  • 2
  • 15
  • 37