Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally apply a ! to a method in JavaScript

Tags:

javascript

Not sure how better to word this (and, consequently, couldn't find previous answers, though I expect this has been answered before), but I'm interested in whether there's a way to turn code like this:

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

To something like the below (not sure how better 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 all the repetition by choosing whether or not to call the return line with a bang?

like image 754
Sasha Avatar asked Dec 15 '15 22:12

Sasha


1 Answers

You could simplify it in other ways:

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

In general, you would want to avoid this method if your function changes any state. However, since in this case you are calling it regardless, there's no harm in caching its value first.

like image 179
Xophmeister Avatar answered Oct 30 '22 13:10

Xophmeister