bxk21
bxk21

Reputation: 192

Inline NOT operator using boolean

I have this snippet of code:

if (bool) {
    return <code that outputs bool>;
} else {
    return !<same code that outputs bool>;
}

Is there a way to convert the above to something like this so that I don't have to write the code twice?

return (bool? !! : !) <code>;

Upvotes: 0

Views: 217

Answers (2)

VLAZ
VLAZ

Reputation: 28979

If you don't want to write the code twice, then extract the result to a variable or to a function

//sample <code that outputs bool>
var result = 

or

function calculateBool(someObj) {
   return someObj.fetchA()
  && someObj.fetchB()
  && someObj.fetchC()
  && someObj.fetchD()
  && someObj.fetchE()
// etc...
}

so you can then simply do

if (bool) {
  return result
} else {
  return !result
}

this can be simplified to

if (!bool) {
  result = !result;
}
return result;

or

return bool? result : !result;

If you prefer to use boolean algebra to do a flip of the result, then you can use XOR. In JavaScript, the XOR operator will work on integers only, so it converts boolean values to 0 or 1 but you can just directly turn those into a boolean again implicitly !!value or explicitly Boolean(value).

Here is how the XOR equation works valueToFlip XOR bool will invert the result for bool = true and valueToFlip being any value. If you want to only flip on bool = false, then you can simply invert it in the equation `valueToFlip XOR NOT bool:

function describeFlip(valueToFlip, bool) {
  const result = Boolean(valueToFlip ^ !bool);
  console.log(`${valueToFlip} ${bool}: ${result}`)
}


describeFlip(true, true);
describeFlip(false, true);
describeFlip(true, false);
describeFlip(false, false);

Upvotes: 0

bxk21
bxk21

Reputation: 192

Found it!

return bool === <code>

I wrote down a truth table and saw this

      code
       T F
      +-+-
     T|T|F
bool  +-+-
     F|F|T

Which is the same table as bool = code

Upvotes: 2

Related Questions