0

I have a piece of code like

if (A[i][j] === 1) 
   A[i][j] = 0;
else 
   A[i][j] = 1;

and I'm wondering how I can optimize it like

var elem = A[i][j]; // obviously A[i][j] is an R-value ... I want an L-value
if (elem === 1) 
   elem = 0;
else 
   elem = 1;

In addition, I'm wondering if there's a single operation that can perform the equivalent of toggling between 0 and 1, the equivalent of

if (elem === 1) 
   elem = 0;
else 
   elem = 1;

Is there some fancy bitwise operation that can do it?

Donald Knuth
  • 145
  • 4
  • 3
    I'm worried about you, Dr. Knuth. – Pointy Oct 15 '15 at 14:58
  • 1
    Anyway the direct answer to your question is that you can't - there's no way to create an alias for an object property. In C you can get the address of something and save that value in a pointer variable; there's nothing like that in JavaScript.. – Pointy Oct 15 '15 at 14:59
  • @Andreas If `A[i][j]` can be anything different to `0` or `1` then, this wouldn't work. – VisioN Oct 15 '15 at 15:00
  • 1
    @VisioN He's asking explicitly for a "fancy bitwise operation" to toggle between 1 and 0. For me this is enough to assume the values will be 1 and 0. But you're absolutely right. If there can be other values than that it won't work. – Andreas Oct 15 '15 at 15:03
  • what are the types and what are the values of `A[i][j]`? – Nina Scholz Oct 15 '15 at 15:21

1 Answers1

1

The comment by @Andreas is a good optimization. Turned into an answer for posterity:

A[i][j] ^= 1;

It only retrieves the value once and applies the result. You still can't get a memory address (JS is reference only), but it limits the number of times you have to access it.

The Bitwise XOR has the nice effect of turning 0 -> 1 and 1 -> 0 when applied with a 1 mask. By doing all the work in one op, you can get the fewest accesses possible.

Edit: As per the discussion, this solution only works when the array is filled with 0 / 1 values.

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
  • Please make a note in your answer following the [discussion in the comments](http://stackoverflow.com/questions/33151712/in-javascript-how-do-i-obtain-a-reference-to-an-element-in-an-array#comment54113329_33151712). – VisioN Oct 15 '15 at 15:04
  • In regards to the inputs always being a 0 / 1? – TbWill4321 Oct 15 '15 at 15:06
  • Yes. It is far not clear that all values in the array are just `0` and `1`. If they are, this solution will definitely work, otherwise not. – VisioN Oct 15 '15 at 15:15