Reputation: 15006
This is what I'm trying to achieve:
var direction = (getState() < state) ? -1 : +1; //check direction
var state = state + direction
But I don't like this solution at all. Would like something like:
var state = (getState() < state) ? state++ : state--;
Upvotes: 0
Views: 43
Reputation: 386654
You could use the ternary without assignment.
getState() < state ? state++ : state--;
or
state += getState() < state || -1;
Upvotes: 1
Reputation: 224942
var state = state + direction
This is either a redeclaration or something that doesn’t work, so
state += direction;
which I guess you can fold into one line if you were satisfied with the post(in|de)crement.
state += getState() < state ? -1 : +1;
and I think that’s as readable as that operation gets.
If you were doing something only slightly different (that involved not changing state
when getState() === state
), you could use Math.sign
!
state += Math.sign(getState() - state);
This is a nice and clean solution, so maybe you can change the problem to suit it. =)
Upvotes: 1