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
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 :
// #1
let boolToNumber = b=> +b*2-1;
// #2
boolToNumber = b => (b<<1)-1;
// #3
boolToNumber = b => b?+b:~b;
//
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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP