TransWikia.com

Whats the shortest way to return a condition as 1 and -1

Stack Overflow Asked by Elias Dal Ben on November 10, 2021

Is there any shorter way to return a condition as 1 if true/truthy and -1 if false/falsy? Maybe using bitwise operators?

The shortest way I can think is:

condition?1:-1

4 Answers

Simply you can try the folowing:

condition ^ (condition - 1)

So when condition is true then that would be:

1 ^ (1 - 1)
 => 1 ^ 0
 => 1

And when condition is false then:

0 ^ (0 - 1)
=> 0 ^ -1
=> -1

Hope this helps.

Answered by OO7 on November 10, 2021

I see those ones :

  • (for the funny transformation)
// #1
let boolToNumber = b=> +b*2-1;
// #2
boolToNumber = b => (b<<1)-1;
// #3
boolToNumber = b => b?+b:~b;
  • And if what really matter for you is the size, make it an 1 char function
// 
let boolToNumber = b=> +b*2-1;
let b = boolToNumber;
let c = true;
b(c)// 4 charaters

Answered by 8HoLoN on November 10, 2021

Assuming condition is a boolean value, we can golf one character:

condition*2-1

(Not that I would recommend to write code like this…)


there's gotta be a shorter way to do than i + (i%2==0?1:-1)

What you actually want is to just toggle the last bit in the number, which can be achieved with XOR:

i^1

Answered by Bergi on November 10, 2021

Just take

+condition || -1

where condition is a boolean value.

Answered by Nina Scholz on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP