Bijan
Bijan

Reputation: 8584

Javascript condense if statement

I have an if statement in javascript that is

if(prop < 0 || trans < 0 || queue < 0 || proc < 0 
    || prop > 1 || trans > 1 || queue > 1 || proc > 1 
    || prop == "" || trans == "" || queue == "" || proc == ""){

Is there a way to condense this? For prop, trans, queue, and proc. I want to create an if statement if the values do not fall to be between 0 and 1 or if it has an empty string value

Upvotes: 0

Views: 371

Answers (3)

rink.attendant.6
rink.attendant.6

Reputation: 46208

Building off of Jordan's answer:

var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);

function checkTruthinessOf(things) {
    return things.every(function(el) {
       return (el < 0 || el > 1 || el === "");
    });
}

See Array.prototype.every()

Upvotes: 4

Shiala
Shiala

Reputation: 486

I picked up this practice from jQuery. It eliminates the extra array and just passes in as many arguments as you like. Then use rink's function to validate all it at once.

var result = checkTruthinessOf(prop, trans, queue, proc);

function checkTruthinessOf(/*unlimited arguments*/) {
   return Array.prototype.every.call(arguments, function(thing) {
       return (thing < 0 || thing > 1 || thing === "");
    });
}

Upvotes: 1

Jordan Foreman
Jordan Foreman

Reputation: 3888

var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);

function checkTruthinessOf(things) {
    var returnValue = false;
    [].forEach.call(things, function(thing){
       if (thing < 0 || thing > 1 || thing == "") returnValue = true;
    });
    return returnValue;
};

Upvotes: 4

Related Questions