Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way of writing v = (v == 0 ? 1 : 0); [closed]

I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

v = (v == 0 ? 1 : 0); 

Can you improve on this?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

like image 395
Ollie Glass Avatar asked Aug 02 '11 11:08

Ollie Glass


People also ask

How to toggle 0 and 1 in JavaScript?

const rotate = (function iife() { let lastValue = 0; return function () { lastValue = 1 - lastValue; return lastValue; }; }()); And yes I kept it simple with 1-lastValue like @Gandalf, because the x%2 stuff is another complexity that just isn't needed yet.

What is|| in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.


2 Answers

You can simply use:

v = 1 - v; 

This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.

Another method that is shorter but uses a less common operator:

v ^= 1; 

Edit:

To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.

like image 191
Guffa Avatar answered Sep 21 '22 19:09

Guffa


Since 0 is a false value and 1 is a true value.

v = (v ? 0 : 1); 

If you are happy to use true and false instead of numbers

v = !v; 

or if they must be numbers:

v = +!v; /* Boolean invert v then cast back to a Number */ 
like image 44
Quentin Avatar answered Sep 18 '22 19:09

Quentin