0

I have difficulty with running a code which checks two criteria in switch case as this code prints 'unknown' since in javascript

['police',false]!=['police',false]

Is there any way to implement this code using switch-case rather than nested ifs?

var option='police';
var urgent=false;

switch([option,urgent])
{
case ['police',true]:
       console.log('police,true');
       call_police_urgent();
       break;
case ['police',false]:
       console.log('police,false');
       call_police();
       break;
case ['hospital',true]:
       console.log('hospital,true');
       call_hospital_urgent();
       break;
case ['hospital',false]:
       console.log('hospital,false');
       call_hospital();
       break;
case ['firestation',true]:
       console.log('firestation,true');
       call_firestation_urgent();
       break;
case ['firestation',false]:
       console.log('firestation,false');
       call_firestation();
       break;
default:
       console.log('unknown');
}
ar2015
  • 5,558
  • 8
  • 53
  • 110

4 Answers4

4

Your code doesn't work because one array literal is never equal to another even if they look the same. There are many ways to solve that, but most of them boil down to converting arrays to something one can compare, e.g. strings:

let str = (...args) => JSON.stringify(args);

switch (str(option, urgent)) {
    case str('police', false):
        console.log('police,false');
        break;
    case str('hospital', true):
        console.log('hospital,true');
        break;
    default:
        console.log('unknown');
}

This works for your simple case, but not in general, because not everything can be stringified.

georg
  • 211,518
  • 52
  • 313
  • 390
2

You can convert an array of options to string:

var option='police';
var urgent=false;

switch([option,urgent].join())
{
case 'police,true':
       console.log('police,true');
       break;
case 'police,false':
       console.log('police,false');
       break;
case 'hospital,true':
       console.log('hospital,true');
       break;
case 'hospital,false':
       console.log('hospital,false');
       break;
case 'firestation,true':
       console.log('firestation,true');
       break;
case 'firestation,false':
       console.log('firestation,false');
       break;
default:
       console.log('unknown');
}
stdob--
  • 28,222
  • 5
  • 58
  • 73
0

i don't know what you are trying to do, but your above code javascript engines and runtime environments with yell at you.

and secondly [] literal can and will never be equal to another [] literal

choose in between this two

var option='police';
var urgent=false;

function first_switch(option,urgent) {
    switch(option) {
    case "police":
        if ( urgent )
            console.log('police,true');
        else
            console.log('police,false');
        break;
    case "hospital":
        if ( urgent )
            console.log('hospital,true');
        else
            console.log('hospital,false');
        break;
    case "firestation":
        if ( urgent )
            console.log('firestation,true');
        else
            console.log('firestation,false');
        break;
    default:
        console.log('unknown');
    }
}

function second_switch(option,urgent) {

    if ( urgent ) {

        switch(option) {
        case "police":
        case "hospital":
        case "firestation":
            console.log(`${option}`, "true");
            break;
        default:
            console.log('unknown');
        }

        return ;
    }

    switch(option) {
    case "police":
    case "hospital":
    case "firestation":
        console.log(`${option}`, "false");
        break;
    default:
        console.log('unknown');
    }
}

first_switch(option,urgent);
first_switch(option, true);

second_switch(option, urgent);
second_switch(option, true);
0.sh
  • 2,659
  • 16
  • 37
0

We can create the same funtionality without using switch cases. We could create a lookup table like:

var emergencyLookupTable = {
  police: [{
      case: true,
      fn: call_police_urgent
    },
    {
      case: false,
      fn: call_police
    }
  ],
  hospital: [{
      case: true,
      fn: call_hospital_urgent
    },
    {
      case: false,
      fn: call_firestation_urgent
    }
  ],
  firestation: [{
      case: true,
      fn: call_firestation_urgent
    },
    {
      case: false,
      fn: call_firestation
    }
  ]
}

And pass this object into emergency which is looking for the correct cases.

function emergency(lookup, option, urgent) {
  if (lookup[option]) {
    lookup[option]
      .filter(function(obj) {
        return obj.case === urgent
      })
      .forEach(function(obj) {
        obj.fn()
      })
  } else {
    console.log('unknown')
  }
}

emergency(emergencyLookupTable, 'police', true)

Working Example

var emergencyLookupTable = {
  police: [{
      case: true,
      fn: call_police_urgent
    },
    {
      case: true,
      fn: call_police_urgent2
    },
    {
      case: false,
      fn: call_police
    }
  ],
  hospital: [],
  firestation: []
}

function emergency(lookup, option, urgent) {
  if (lookup[option]) {
    lookup[option]
      .filter(function(obj) {
        return obj.case === urgent
      })
      .forEach(function(obj) {
        obj.fn()
      })
  } else {
    console.log('unknown')
  }
}

function call_police_urgent() {
  console.log('call the police!')
}

function call_police_urgent2() {
  console.log('call the police again!')
}

function call_police() {
  console.log('call the police..')
}

emergency(emergencyLookupTable, 'police', true)
emergency(emergencyLookupTable, 'police', false)
Roman
  • 4,922
  • 3
  • 22
  • 31