use string "includes()" in switch Javascript case
Asked Answered
O

5

30

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

Obe answered 15/4, 2017 at 7:29 Comment(0)
S
21

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);
Sperrylite answered 15/4, 2017 at 7:34 Comment(1)
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 !Obe
L
28

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
}
Lafontaine answered 15/4, 2017 at 7:34 Comment(3)
Why not use it in practice?Volotta
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.Sperrylite
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.Obe
S
21

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);
Sperrylite answered 15/4, 2017 at 7:34 Comment(1)
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 !Obe
M
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.

Morehead answered 15/11, 2017 at 17:41 Comment(2)
That's super beautiful and neat. Matches exactly my use case.Altdorfer
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 inputUndeceive
S
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
Synecious answered 20/7, 2020 at 4:45 Comment(1)
I think this is brilliant!Bethink
O
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];
    }
})
Obstipation answered 27/10, 2023 at 6:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.