Convert true and false in Coffeescript to 1 and -1 respectively

4.3k views Asked by At
if x < change.pageX # pageX is cross-browser normalized by jQuery
            val = Number(elem.text())
            return elem.text(o.max) if val + o.step > o.max
            return elem.text(o.min) if val + o.step < o.min
            elem.text(val + o.step)
else x > change.pageX
  # same thing, only - instead of +

(Coffee Script, but you get the idea). I'm looking for a trick to take a boolean and convert it to either 1 (true) or -1 (false). that way I can do val + converted_bool * o.step and save an if.

7

There are 7 answers

4
Quentin On

Sounds like a job for a conditional (ternary) operator

if true then 1 else -1
1
if false then 1 else -1
-1
1
jfriend00 On

Are you looking for anything beyond this plain javscript:

boolVal ? 1 : -1

Or, in function form:

function convertBool(boolVal) {
    return(boolVal ? 1 : -1);
}

Straight math involving boolean values converts true to 1 and false to 0:

var x,y;
x = false;
y = 2;
alert(y + x);  // alerts 2

x = true;
y = 2;
alert(y + x);  // alerts 3

If performance is of interest, here's a jsperf test of four of the methods offered as answers here. In Chrome, the ternary solution is more than 7x faster.

2
CamelCamelCamel On

Ah Ha!

2 * (!!expression) - 1

0
KL-7 On

I smth like that will work:

b2i = (x) -> if x then 1 else -1
b2i(true)  # => 1
b2i(false) # => -1

That function definition will result into that (not very exciting) JavaScript:

var b2i;

b2i = function(x) {
  if (x) {
    return 1;
  } else {
    return -1;
  }
};

Note that CoffeeScript ? is existential operator so

x ? 1 : -1

will convert to smth a bit unexpected as

if (typeof x !== "undefined" && x !== null) {
  x;
} else {
  ({ 1: -1 });
};
3
dstarh On

(~true)+3 and (~false) will give you 1 and negative one :)

3
AudioBubble On

You can do it like this...

+x||-1

  • If x===true, the +x is 1, and the -1 is short-circuited.

  • If x===false, the +x is 0, and the -1 is returned.


Here's another way...

[-1,1][+x]
  • If x===true, [+x] will grab index 1 of the Array.

  • If x===false, [+x] will grab index 0 of the Array.

2
bennedich On

You can also type javascript inside coffeescript:

foo = `bar ? 1 : -1`