Conditionally apply a! to a method in JavaScript

Not sure how best to say this (and therefore could not find the previous answers, although I expect it to be the answer earlier), but I am wondering if there is a way to make such code:

if ( this.props.mailboxFilter == 'sent' ) { return this.currentUser.canActOnBehalfOf( m.senderID ); } else { return !this.currentUser.canActOnBehalfOf( m.senderID ); } 

Something like below (not sure how best to express it):

 var bangOrNot = this.props.mailboxFilter == 'sent ? '!' : ''; bangOrNot( this.currentUser.canActOnBehalfOf( m.senderID ) ); 

As in, is there a way to avoid the extended if / else syntax and the whole repetition by choosing whether to call the return string with a hit?

+7
javascript
source share
5 answers

You can simplify it in other ways:

 var response = this.currentUser.canActOnBehalfOf(m.senderID); return this.props.mailboxFilter == 'sent' ? response : !response; 

In general, you would like to avoid this method if your function changes any state. However, since in this case you call it regardless of whether there is any harm in caching its value in the first place.

+9
source share

If this.currentUser.canActOnBehalfOf( m.senderID ) always returns a boolean, you can do XOR.

 return (this.props.mailboxFilter != 'sent') ^ this.currentUser.canActOnBehalfOf(m.senderID); 

XOR boolean with true makes NOT. And XOR with false creates a buffer that maintains the same value.

Note that I changed == to != .

And just make sure you add comments to this part of the code if you intend to actually use it. It is not so easy to read this code after a while.

Update

As Bergi, it is recommended to use Boolean XOR != To return a Boolean value.

 return (this.props.mailboxFilter != 'sent') != this.currentUser.canActOnBehalfOf(m.senderID); 

And of course, if it can be used with Boolean XNOR, just replace both != With == in the code above.

+5
source share

You want to use the logical XNOR operator here - also known as equivalence:

 return this.currentUser.canActOnBehalfOf(m.senderID) == (this.props.mailboxFilter == 'sent'); 
+3
source share

There are many good comments on why or why NOT to do such a thing. I assume that the OP has good reason to want to apply a hit (!) Before the result of calling the function. My answer is rather a technical solution to the OP question.

 function bang(r) { return !r; } function notBang(r) { return r; } function canActOnBehalf() { return true; } var filter = 'notsent'; var f = (filter == 'sent' ? bang : notBang); f(canActOnBehalf('whatever')); 
0
source share

Assuming you are using javascript, you can use the eval method to evaluate the javascript line of code. You can conditionally apply a hit to the front of the line, and then return the result of eval .

-4
source share

All Articles