Jihyun Moon
Jihyun Moon

Reputation: 25

How can I refactor repetitive switch statement in javascript

I have the following switch statement. But there are repeated codes here and I want to get rid of this. please refactor this code.

var something;
switch(alphabet) {
  case "A":
     something.aa = true;
     something.bb = false;
     something.cc = false;
     break;
  case "B":
     something.aa = false;
     something.bb = true;
     something.cc = false;
     break;
  case "C":
     something.aa = false;
     something.bb = false;
     something.cc = true;
     break;
}

Upvotes: 1

Views: 963

Answers (4)

truefalse10
truefalse10

Reputation: 334

How about leaving the switch statement completely out?

var something = {
  aa: alphabet === "A",
  bb: alphabet === "B",
  cc: alphabet === "C"
}

Upvotes: 3

charlietfl
charlietfl

Reputation: 171689

One approach would be to use an array of the keys and a loop that compares that letter to the key with whatever logic is applicable. In your example it would be a simple includes() or startsWith()

Something like:

const keys = ['aa','bb', 'cc'];
const lower = alphabet.toLowerCase();
keys.forEach(k => something[k] = k.includes(lower))

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386680

You could take an object wthe targets for true, like

var targets = {
        A: 'aa',
        B: 'bb',
        C: 'bb',
    },
    something = { aa: false, bb: false, cc: false };

// usage
if (alphabet in targets) something[targets[alphabet]] = true;

Upvotes: 0

Lord_Rhaziel
Lord_Rhaziel

Reputation: 81

So, at any point in time, only one case will be true, right. Keeping that in mind, you can do the following:

var something = {aa:false,bb:false,cc:false},
switch(alphabet) {
  case "A":
     something.aa = true;
     break;
  case "B":
     something.bb = true;
     break;
  case "C":
     something.cc = true;
     break;
}

Hope that helps. :-)

Upvotes: 0

Related Questions