Alexander Mills
Alexander Mills

Reputation: 100486

Logical reduction of code to a one-line expression

This one seems to be real. How can I reduce this to one if statement?

    let combined = true;

    if(earlyCallback){
      combined = self.allChildBlocksCompleted;
    }

    if (self.parent && combined) {  // I want to put everything here

    }

Is this correct?

 if(self.parent || (earlyCallback && self.allChildBlocksCompleted)){

  }

I think it's right but I can't tell right now.

Upvotes: 1

Views: 49

Answers (2)

Patrick87
Patrick87

Reputation: 28332

This is equivalent to the accepted answer:

if (self.parent && (!earlyCallback || self.allChildBlocksCompleted)) {

You might consider this simpler than other answers that require the hard-coded literal true and the ternary operator. It's also shorter by a few characters:

if (self.parent && (earlyCallback ? self.allChildBlocksCompleted : true)) {

You can "simplify" it further by exchanging one "or" for an extra not and an "and" using De Morgan:

if (self.parent && !(earlyCallback && !self.allChildBlocksCompleted)) {

Upvotes: 1

Faly
Faly

Reputation: 13356

I prefer do it like below:

if (self.parent && (earlyCallback ? self.allChildBlocksCompleted : true )) { }

Upvotes: 2

Related Questions