CamelCamelCamel
CamelCamelCamel

Reputation: 5200

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

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.

Upvotes: 0

Views: 4407

Answers (7)

Quentin
Quentin

Reputation: 944116

Sounds like a job for a conditional (ternary) operator

if true then 1 else -1
1
if false then 1 else -1
-1

Upvotes: 5

bennedich
bennedich

Reputation: 12371

You can also type javascript inside coffeescript:

foo = `bar ? 1 : -1`

Upvotes: 0

user1106925
user1106925

Reputation:

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.

Upvotes: 10

jfriend00
jfriend00

Reputation: 707816

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.

Upvotes: 0

dstarh
dstarh

Reputation: 5086

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

Upvotes: 1

KL-7
KL-7

Reputation: 47658

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 });
};

Upvotes: 1

CamelCamelCamel
CamelCamelCamel

Reputation: 5200

Ah Ha!

2 * (!!expression) - 1

Upvotes: 0

Related Questions