Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any justification for `x < y && y > x`?

I was going through some Javascript code used to validate form entry and I noticed an if statement that read if (!(x < y && y > x)) {...}

My initial thought was that this sort of tautological construction is completely redundant, and one of the two comparisons should be dropped. Just in case there's a chance I'm wrong and there's actually more to it, though, I thought I'd ask.

My other thought was that it might be a case of some idiom that is necessary in another language, which the programmer has here just brought along with them to Javascript out of habit (although I'd be surprised to find a language where something like this is required that is also used in any sort of environment).

EDIT

The specific code is in a function to test that the start and end dates for a submitted event are possible (i.e. the end date is after the start date). The actual example reads if(!(start_time < end_time && end_time > start_time)) {...} where both start_time and end_time are DateTime values.

EDIT 2

Not a duplicate of this question as in this case the issue is the need to test two conditions that appear mutually inclusive in an if statement, whilst in that case the issue is how to make an if statement resolve that appears to require two mutually exclusive conditions to be simultaneously true.

like image 367
08915bfe02 Avatar asked Aug 07 '18 06:08

08915bfe02


1 Answers

It looks like a pattern to allow falsy values, which convert to a number (without NaN, like '' or null).

function f(x, y) {
    return [!(x > y && y < x), x <= y, x < y || x === y].join(' ');
}

console.log(f(1, 2));                 //  true
console.log(f(2, 1));                 // false
console.log(f(1, 1));                 //  true
console.log(f('', 1));                //  true
console.log(f(1, ''));                // false
console.log(f('', ''));               //  true
console.log(f(undefined, undefined)); //  true \
console.log(f(1, undefined));         //  true  different values by using other comparisons
console.log(f(undefined, 1));         //  true /
console.log(f(null, null));           //  true
console.log(f(1, null));              // false
console.log(f(null, 1));              //  true
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 153
Nina Scholz Avatar answered Sep 30 '22 12:09

Nina Scholz