faino
faino

Reputation: 3224

Conditional operator, simplified way to check result after addition

I'm working on a game for a friend, and in the stat building part of the class I have a part that adds basic modifiers to the stats based on the class (warrior, mage, etc) however the final stat cannot be less than zero.

Currently there's this:

this.stats[i] += type[i];
if(this.stats[i] < 0) {
    this.stats[i] = 0;
}

Which is fine, a bit redundent, but I was wondering if it's possible to do this in a single line. I doubt it, but I was curious to see if I may be wrong.

Something like:

this.stats[i] += type[i] < 0 ? // etc;

But I know that will just run the conditional before adding the variable to the current int. Also, yes, working with integers only, no floats or strings or whatever, that's taken care of elsewhere.

Upvotes: 1

Views: 38

Answers (2)

Oriol
Oriol

Reputation: 288550

Assignments like += return the assigned value. If the operator precedence is not like you want, just add parentheses.

if((this.stats[i] += type[i]) < 0) this.stats[i] = 0;

But probably a Math.max is clearer:

this.stats[i] = Math.max(0, this.stats[i] + type[i]);

Upvotes: 4

Viktor Kukurba
Viktor Kukurba

Reputation: 1370

You can write in one line but it won't be very simple, cause you have to check sum of this.stats[i] + type[i]

this.stats[i] = (this.stats[i] + type[i]) < 0 ? 0 : (this.stats[i] + type[i]).

So, you can add variable here

var sum = this.stats[i] + type[i];
this.stats[i] = sum < 0 ? 0 : sum;

Upvotes: 1

Related Questions