skip to Main Content

How can I implement this behavior in JavaScript Switch Statements

expression = 'all' or '1' or '2' 

switch (expression)
{
   case "all" : print case 1 and case 2 
      
   case "1" : print only case 1 

   case "2" print only case 2
}

How can I do that? If there’s no way to do something like that in JavaScript, I want to know an alternative solution.

5

Answers


  1. You should read this first: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

    let text = "all" // this could be '1' or '2';
    
    switch (text) {
      case '1':
        console.log('print case 1');
        break;
      case '2'
        console.log('print case 2');
        break;
      default:
        console.log('print case 1 and 2');
    }
    

    This is essentially how you would handle that in Javascript.
    Now, if you want types that is another conversation.

    Login or Signup to reply.
  2. Maybe a ‘mapping’ object would fit your needs.

    Check the key on the object, call that case if needed.

    On all, loop over Object.values(obj) to call all the cases

    const mapper = {
      "1": () => console.info('Do case 1'),
      "2": () => console.info('Do case 2')
    }
    
    const test = (i) => {
        if (i === 'all') {
            Object.values(mapper).forEach(c => c());
        } else {
            if (mapper[i]) mapper[i]();
            else console.error('No case for', i);
        } 
    }
    
    test("1");
    test("2");
    test("all");
    test("9");
    Login or Signup to reply.
  3. You can use the switch statements like this:

    expression = 'all'  // "1" or "2"
    
    switch (expression) {
       case "all":
          console.log("1")
          console.log("2")
          break;
    
       case "1":
          console.log("1");
          break;
    
       case "2":
          console.log("2");
          break;
    
       default:
          console.log("Default case");
    }
    

    Please note that a block will execute until a break statement is encountered. If you do not use the break statement, the execution will fall through. For example, this statement will print 1, 2, and then 1 again because we are not using the break statement in the first case:

    expression = ‘all’ // "1" or "2"

    switch (expression) {
       case "all":
          console.log("1");
          console.log("2");
    
       case "1":
          console.log("1");
          break;
    
       case "2":
          console.log("2");
          break;
    
       default:
          console.log("Default case");
    }
    
    Login or Signup to reply.
  4. You can construct your own "switch" kind of

    const betterSwitch = value => cases => {
      if (value === 'all') {
        Object.values(cases).forEach(Reflect.apply)
      } else {
        cases[value]()
      }
    }
    
    const expression = 'all'
    betterSwitch(expression)({
      '1': () => {
        console.log('1')
      },
      '2': () => {
        console.log('2')
      }
    })

    Or you can use a reverse switch trickery

    const expression = 'all'
    
    const allOr = v => ['all', v].includes(expression)
    
    switch (true) {
      case allOr('1'):
        console.log('1')
        break
      case allOr('2'):
        console.log('2')
        break
    }
    Login or Signup to reply.
  5. You could take two condition instead.

    function fn(expression) {
       if (expression === '1' || expression === 'all') console.log(1);
       if (expression === '2' || expression === 'all') console.log(2);
    }
    
    fn('1');
    console.log('----------');
    fn('2');
    console.log('----------');
    fn('all');
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search