0

my mind is blank and I can't think of the solution...

I have the following code:

if (onlySelected === true) {
    if (r.selected == true) {
        result.push(pushValue);
    }
}
else {
    result.push(pushValue);
}

how can I simplify this code into this:

if (condition) { result.push(pushValue) } 

6 Answers 6

8

Try this:

if (!onlySelected || r.selected){
    result.push(pushValue);
}

or this if you absolutely need the type equality and not just truthiness:

if (onlySelected !== true || r.selected){
    result.push(pushValue);
}
Sign up to request clarification or add additional context in comments.

Comments

0
if(onlySelected === false || r.selected == true) {
    result.push(pushValue);
}

3 Comments

!== true is not equal to === false
@Bergi That makes absolutely no sense to me, so would you mind explaining why?
For example 5 !== true, but 5 is not === false.
0
(!onlySelected || r.selected) && result.push(pushValue);

3 Comments

Using !onlySelected is going to result in type conversion where necessary. Judging from the fact they used the === comparator, rather than simply ==, this seems incorrect.
@AnthonyGrist That's true, I was supposing that onlySelected was intended as a boolean value. Same for r.selected.
onlySelected and r.selected are indeed both boolean.
0
if( (onlySelected === true && r.selected === true) || 1) {
    result.push(value)
}

Comments

0

I think this would work:

if(!onlySelected || (onlySelected && r.selected))
    result.push(pushValue);

1 Comment

If !onlySelected is false, onlySelected is true so you can eliminate that one.
0

Hm, this is what I made it to.

onlySelected === !0 ? r.selected == 1 && result.push(pushValue) : result.push(pushValue)

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.