Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if number change from negative to positive or positive to negative

How to detect if positive or nagative changes ?

Example :

1 change to 2 = false

0 change to 1 = false

Because both are positive numbers

1 change to -1 = true

0 change to -1 = true

Because positive change to negative

-1 change to 0 = true

-1 change to 1 = true

Because negative change to positive

I do like..

var a_test,b_test;
if(a<0) {
    a_test = 'negative';
} else {
    a_test = 'positive';
}
if(b<0) {
    b_test = 'negative';
} else {
    b_test = 'positive';
}

if(a_test!==b_test) {
    alert('Yeah!');
}

For test : http://jsfiddle.net/e9QPP/

Any better coding for do something like this ?


Wiki : A negative number is a real number that is less than zero

like image 266
l2aelba Avatar asked Dec 09 '22 10:12

l2aelba


2 Answers

According to the Zen of Python,

Readability counts.

So, I present more readable and code-review passing version

if (a < 0 && b >= 0 || a >= 0 && b < 0) {
    alert("Yeah");
}
like image 118
thefourtheye Avatar answered Dec 11 '22 00:12

thefourtheye


You seem to want

if (a*b<0) alert('Yeah!');

If you want to consider 0 as a positive number, you may use

if (a*b<0 || (!(a*b) && a+b<0)) alert('Yeah!');
like image 30
Denys Séguret Avatar answered Dec 11 '22 00:12

Denys Séguret