2

Is there more elegant way for this if?

   if (err.code === 'CONFLICT-GROUP-GENERAL' ||
    err.code === 'CONFLICT-USER-GENERAL' ||
    err.code === 'CONFLICT-FORM-GENERAL' ||
    err.code === 'CONFLICT-PROJECT-GENERAL' ||
    err.code === 'CONFLICT-TEMPLATE-GENERAL') {}
Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
dariashka
  • 175
  • 1
  • 13

2 Answers2

6

I would be better off with an array with all the codes and use indexOf to check if it's greater than -1:

if (['CONFLICT-GROUP-GENERAL', 'CONFLICT-USER-GENERAL', 'CONFLICT-FORM-GENERAL', 'CONFLICT-PROJECT-GENERAL', 'CONFLICT-TEMPLATE-GENERAL'].indexOf(err.code) > -1) {
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
3

This trick seems to me more elegant (using an array and indexOf):

var conflicts = ['CONFLICT-GROUP-GENERAL',
                    'CONFLICT-USER-GENERAL',
                    'CONFLICT-FORM-GENERAL',
                    'CONFLICT-PROJECT-GENERAL',
                    'CONFLICT-TEMPLATE-GENERAL'];

if (conflicts.indexOf(err.code) !== -1) {
    doSomething();   
}

If you are using ES7 then you can use includes() instead of indexOf. This will be more "expressive":

var conflicts = ['CONFLICT-GROUP-GENERAL',
                    'CONFLICT-USER-GENERAL',
                    'CONFLICT-FORM-GENERAL',
                    'CONFLICT-PROJECT-GENERAL',
                    'CONFLICT-TEMPLATE-GENERAL'];

if (conflicts.inclues(err.code)) {
    doSomething();
}

Note that includes() will not be suported by all browsers.

EDIT:

Another alternative: Using a switch. This way:

switch (err.code) {
    case 'CONFLICT-GROUP-GENERAL',:
    case 'CONFLICT-USER-GENERAL',:
    case 'CONFLICT-FORM-GENERAL',:
    case 'CONFLICT-PROJECT-GENERAL',:
    case 'CONFLICT-TEMPLATE-GENERAL':
        doSomething();
        break;
}

The code above will execute the doSomething() function when err.code is equal to one of specified strings in each case.

Bruno Peres
  • 15,845
  • 5
  • 53
  • 89