0

I am refactoring a switch statement in which I am performing am if conditional within one of the cases where the if will break the switch case and the else will return.

Is it possible to perform this as a quicker conditional such as a Ternary or something else, rather than a standard if/else?

Original

let someCondition;

// someCondition is set at some point

switch(toSwitchOn) {
    case myCase:
        if (someCondition) {
           sendObj({someKey: 'someVal', condition: true});
           break;
        } else {
           sendObj({condition: false});
           return false;           
        }
}

Refactored so far

let someCondition;

// someCondition is set at some point

switch(toSwitchOn) {
    case myCase:
        sendObj({
           ...!!someCondition && {someKey: 'someVal'},
           condition: !!someCondition
        });
     
        if (someCondition) { break; } else {return false}
}
physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • 2
    What's the point of a `switch` with just one `case`? That should just be `if`. – Barmar Jan 09 '23 at 08:31
  • 1
    There's no extra points for creating more terse code if it becomes more confusing. The original code is much more readable than the refactored version. – Barmar Jan 09 '23 at 08:33
  • 1
    What @Barmar said (re `switch` with one `case`). But also: What's wrong with the first version? It's clear, easy to read, easy to debug, ... – T.J. Crowder Jan 09 '23 at 08:33

3 Answers3

0

It depends on what "performing" means to you, but your code should be clear and easy to read, as other people have already answered in the comments.

You can take a look at these topics: Definition of 'clean code' and To ternary or not to ternary?

Ah Hu
  • 46
  • 7
-1

you can do something like this

let someCondition;

// someCondition is set at some point

switch(true) {
    case someCondition:
         sendObj({someKey: 'someVal', condition: true});
         break;
    default:
         sendObj({condition: false});
         return false;           
    }
RA17H45M40S
  • 113
  • 1
  • 6
-1

try this:

let someCondition

// someCondition is set at some point

switch (toSwitchOn) {
    case myCase: {
        const result = handleCondition()
        if (result) break
        else return false
    }
}
function handleCondition() {
    let obj, result
    if (someCondition) {
        obj = { someKey: "someVal", condition: true } 
        result = true
    } else {
        obj = { condition: false }
        result = false
    }
    sendObj(obj)
    return result
}
Phap
  • 17
  • 2