42
AllenII
7y

How i used to toggle a boolean:

foo ? false : true;

How i decided to toggle a boolean last night:

foo = !foo

I wondered why i only just thought of that.

Comments
  • 0
    @No-one i wish nobody really replied 😞😂😂
  • 1
    Ehh, at least i can say I'm progressing
  • 6
    You can xor it for the swag :)
    boolean ^= 1;

    XOR:
    x1 x2 u
    0 0 0
    0 1 1 *
    1 0 0
    1 1 0 *

    In your case x1 is the variabile and x1 is always 1 so you'll have the * cases that basically it's a NOT :)

    It's the same simplified bitwise trick to swap two variables without a third variable

    a ^= b
    b ^= a
    a ^= b

    For example, if a = 5 = 0101 and b = 3 = 0011

    The first xor produces
    a = 0110
    The second with the new a value
    b = 0101 = 5
    And the third with the new b
    a = 0011 = 3
  • 0
    @localghost. Is this doable in JavaScript? If yes, i would try it just to see it work
  • 1
    @AllenII Yes it works, you can test it on the fly writing in your browser:
    javascript: a=5; b=3; alert(a+" "+b); a^=b; b^=a; a^=b; alert(a+" "+b);
  • 0
    @localghost I'll remember that, thanks
  • 2
    I actually thought that looked cute. It looks more sympathetic, like you are politely asking it to change this value, whereas the negation looks more like that poor variable had done something wrong.
    I'll start using your notation from now on!
  • 0
    @matsaki95 that took me far too long to catch on to that joke 😂😂😂
  • 2
    It's better than my company's current codebase:

    boolean = boolean || true;

    😎😎😎😎
  • 1
    @antonis179 how does that even work? If the boolean was true it would remain true after that statement. Did you mean to xor it?
  • 1
    @siljamicke i was thinking the same thing
  • 0
    @siljamicke no. Fucking. Idea. Found it like this didn't make it ;)

    A colleague is rewriting that part thankfully!!!
  • 0
    @antonis179 tell your colleague that it should be:
    if(boolean) boolean = boolean && false;
    else boolean = boolean || true
  • 0
    Ngl, that's lowkey pretty cool...

    wHY DIDNT I THINK OF THAT
  • 0
    @HyperPie referring to whom or what exactly?
  • 1
    @AllenII Your advanced mathematical wizardry
  • 0
    @HyperPie wouldn't call it that exactly, but thanks
  • 0
Add Comment