32

In Javascript, is there a way to achieve something similar to this ?

const databaseObjectID = "someId"; // like "product/217637"

switch(databaseObjectID) {
    case includes('product'): actionOnProduct(databaseObjectID); break;
    case includes('user'): actionOnUser(databaseObjectID); break;
    // .. a long list of different object types
}

This is more a curiosity question to understand the possibilities of switch / case, as in this particular case I have solved my problem using const type = databaseObjectID.split('/')[0]; and apply the switch case on type

0

6 Answers 6

29

This will work, but it shouldn't be used in practice.

const databaseObjectID = "someId"; // like "product/217637"

switch(true) {
    case databaseObjectID.includes('product'): actionOnProduct(databaseObjectID); break;
    case databaseObjectID.includes('user'): actionOnUser(databaseObjectID); break;
    // .. a long list of different object types
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why not use it in practice?
Because it is a hack and not necessarily easier to read than a set of if/elseifs which lack the break making it shorter code to boot.
thanks. Actually, I didn't want to use a set of if / elseif as with my usual linting rules, I would end us using two lines per if / elseif. As my list of datatypes is potentially long, I was looking for something with just one line per type.
22

You usage would be considered an abuse of case.

Instead just use ifs

     if (databaseObjectId.includes('product')) actionOnProduct(databaseObjectID); 
else if (databaseObjectId.includes('user'))    actionOnUser(databaseObjectID); 
// .. a long list of different object types

If the ObjectId contains static content around the product or user, you can remove it and use the user or product as a key:

var actions = {
  "product":actionOnProduct,
  "user"   :actionOnUser
}

actions[databaseObjectId.replace(/..../,"")](databaseObjectId);

1 Comment

The first proposition does not suit me as my linting rule would not allow me to have such presentation, and I want to avoid having two lines per data type. However, second proposition suits me well ... Thanks !
17

Sorry, I'm a noob so someone will probably have to clean this up, but here is the idea. Pass to a function to check and return a category then use the switch.

function classify(string){
  var category = categorize(string);
  switch (category) {
    case 'product':
      console.log('this is a product');
      break;
    case 'user':
      console.log('this is a user');
      break;
    default:
      console.log('category undefined');    
  }
}

function categorize(string){
  if (string.includes('product')){
    return 'product';
  }
  if (string.includes('user')){
    return 'user';
  }
}

classify("product789");
classify("user123");
classify("test567");

Sorry, as well, for not matching your example.

2 Comments

That's super beautiful and neat. Matches exactly my use case.
Your solution would work; but here @Bertrand Engogram is having a long list of different object types, so why should he write both if & switch statements if he can achieve the same using if_else statements only? You could possibly use a for loop in your categorize() function to reduce the same existing code by taking an object or an array as an input
6

Question:

use string “includes()” in switch Javascript case

While the includes() method will work, it is case sensitive, and just matches any characters. I have found a Regex solution that I like much better, and provides a lot of flexibility. For example, you could easily change this to match only WORDS.

var sourceStr = 'Some Text and literaltextforcase2 and more text'

switch (true)  {  // sourceStr

  case (/LiteralTextForCase1/i.test(sourceStr)):
      console.log('Case 1');
      break;

  case (/LiteralTextForCase2/i.test(sourceStr)):
    console.log('Case 2');
    break;

  default:
      console.log('ERROR No Case provided for: ' + sourceStr);
};

//-->Case 2

1 Comment

I think this is brilliant!
1

This is a very late answer but this is what I used:

const valueToCheck = 'abc';

const caseMap = {
    'a': console.log('a'),
    'b': console.log('b'),
}

Object.keys(caseMap).forEach(val => {
    if(valueToCheck.includes(val)) {
        caseMap[val];
    }
})

Comments

-1

I use:

function classify(string){
  if (string.includes("case 1")) return "Case 1"
  if (string.includes("case 2")) return "Case 2"
  //...
}
switch (classify(string)) {
  case "Case 1":
    //...
    break;
  case "Case 2":
    //..
  default:
    break;
}

You may think: But if I need to use the if clauses, then what's the point? I think this helps make the switch statement clearer. Plus that you may need to reuse the classify function elsewhere when the code grows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.