How to use CONST when there are several conditions

therefore, I am on a train in the circuit and want to start avoiding it at all costs.

The problem I see is the following example: how to use const in a situation with more than two forks in a logical tree. what's the equivalent pattern with const?

function getResult(input) {
    let result;

    switch (input): {
        case (1): { result=x;}
        case (2): { result=y;}
        case (3): { result=x;}
        ...etc
    }

//...additional conditionals and functions depending on the outcomes of switch statement

}

thank,

-6
source share
3 answers
 const result = [x,y,x][input - 1];

This is the array accessed by the index.

-2
source

Although I do not always agree with “avoidance letat all costs,” I would say that the best alternative for using an operator switchis to put it in a separate function and use it return.

, . , , .

const getInnerResult = (x, y, input) => {
  switch (input) { 
    case 1: 
    case 3:  return x;
    case 2:  return y;
    default: return null; 
  }
}

const getResult = function(input) {
  const result = getInnerResult("a", "b", input);
  
  // Other logic using the `result` variable
  return result ? result.toUpperCase() : "-";
};


console.log(getResult(2));
console.log(getResult(5));
Hide result
+1

let. Const , . , url http- (https://your.domain.here/).

let var , , , , /.

switch :

switch (input) {
    case 1: {
        result=x;
        break;
    }
    case 2: {
        result=y;
        break;
    }
    case 3: {
        result=x;
        break;
    }
    default:
        break;
}
0

Source: https://habr.com/ru/post/1682335/


All Articles