Simha Chalam
Simha Chalam

Reputation: 591

how to write this code best way,which has so many if conditions in javascript?

I am get where condition(value) from getcondition(req, Sequelize)

code is:

  options.where = getcondition(req, Sequelize);
       options.include = [{
                model: hp_builders,
                required: true
            }, { ....  },{ .... }]




 hp_property.findAndCountAll(options, {
            subQuery: false
        }).then(function(result) {
res.json(result);
});

so for different requests .i have to assign different value in options.where = getcondition(req, Sequelize);

so how can i write in an effective manner for getcondition(req, Sequelize);

my getcondition(req, Sequelize) function code is:

function getcondition(req, Sequelize) {
    var condition = JSON.parse(req.query.selector);
    if (condition.hasOwnProperty("city_id")) {
        if (condition.hasOwnProperty("Inhibition")){
            console.log(JSON.stringify(condition));
            return {
                $and: [{
                        hp_city_id: condition.city_id
                    },
                    Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"),
                ]
            }
        }
        if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];
            return {
                $and: [{
                        hp_city_id: condition.city_id
                    },
                    Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),
                    Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange)
                ]
            }
        }
        if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {
            return {
                $and: [{
                        hp_city_id: condition.city_id
                    },
                    Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")")
                ]
            }
        } else if (condition.hasOwnProperty("budgetPrice") && !condition.hasOwnProperty("bedrooms")) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];
            return {
                $and: [{
                        hp_city_id: condition.city_id
                    },
                    Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange)
                ]
            }
        }
        return {
                hp_city_id: condition.city_id
        }
    }
    else if (condition.hasOwnProperty("id")) {
        if (condition.hasOwnProperty("Inhibition")){
            console.log(JSON.stringify(condition));
            return {
                $and: [{
                        hp_builders_id: condition.id
                    },
                    Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"),
                ]
            }
        }
        if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];
            return {
                $and: [{
                        hp_builders_id: condition.id
                    },
                    Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),
                    Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange)
                ]
            }
        }
        if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {
            return {
                $and: [{
                        hp_builders_id: condition.id
                    },
                    Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")")
                ]
            }
        } else if (condition.hasOwnProperty("budgetPrice" && !condition.hasOwnProperty("bedrooms"))) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];
            return {
                $and: [{
                        hp_builders_id: condition.id
                    },
                    Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange)
                ]
            }
        }
        return {
            hp_builders_id: condition.id
        }
    } else if (condition.hasOwnProperty("location_id")) {
        console.log(JSON.stringify(req.query.selector) + ".....");
        return {
            hp_location_id: condition.location_id
        }
    }
}

Upvotes: 0

Views: 139

Answers (4)

matthieusb
matthieusb

Reputation: 505

Using switch statements could actually help but in your case most conditions are too complicated. For syntax, follow this link : W3Schools javascript switch

What you could do in term of good practices would be creating sub_functions called in each condition. You can also gather a few tasks in your sub-functions and add if statements. This will lighten your function. In term of good practices however, your sub-functions should not be redundant, try and choose carefully so that each function you write has a different purpose than the others.

EDIT : I previously said that your function should only have one return statement. This is not entirely true, as this convention can sometime make the code less easy to understand. That being said, it is a question of personal taste. A good compromise would be to put a return statement at the beginning of the function for error cases, and use another return statement at the end for classic result return.

You could also use pattern matching. See this link : Pattern matching with javascript.

Upvotes: 1

denysdovhan
denysdovhan

Reputation: 986

There are awesome JavaScript switch Statements. Use them when you have such terrible conditions.

UPD: Example of using switch:

function getcondition(req, Sequelize) {
  const condition = JSON.parse(req.query.selector);

  switch (true) {
    case (condition.hasOwnProperty('city_id')): {
      // ...
    }
    case (condition.hasOwnProperty('id')): {
      // ...
    }
    case (condition.hasOwnProperty('location_id')): {
      // ...
    }
  }
}

Note that the switch-case will break at the first occurance of any true statement. So, be careful while using break and return statements.

Upvotes: 1

Simha Chalam
Simha Chalam

Reputation: 591

i tried like this but i want more less and good code,plase give some other corrections

function getcondition1(req, Sequelize) {

var condition = JSON.parse(req.query.selector);

if (condition.hasOwnProperty("city_id")) {
   return comparison(condition,"city_id","hp_city_id");
}

else if (condition.hasOwnProperty("id")) {
    return comparison(condition,"id","hp_builders_id");
}

else if (condition.hasOwnProperty("location_id")) {
    return comparison(condition,"location_id","hp_location_id");
}

}

function comparison(condition,id,dbId){
        var obj={};
        var andCondition=[];
        var subCondition={};

        if (condition.hasOwnProperty("Inhibition")){
            subCondition[dbId]=condition.id;
            andCondition.push(subCondition,Sequelize.literal("`hp_property`.`hp_property_inhibition_status_id` IN (" + condition.Inhibition + ")"));

            obj['$and']=andCondition;

            return obj;

        }

        if (condition.hasOwnProperty("bedrooms") && condition.hasOwnProperty("budgetPrice")) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];

            subCondition[dbId]=condition.id;
            andCondition.push(subCondition,Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"),Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange));

            obj['$and']=andCondition;

            return obj;
        }

        if (condition.hasOwnProperty("bedrooms") && !condition.hasOwnProperty("budgetPrice")) {

            subCondition[dbId]=condition.id;
            andCondition.push(subCondition,Sequelize.literal("`hp_unit_details`.`hp_unit_type_id` IN (" + condition.bedrooms + ")"))
            obj['$and']=andCondition;

            return obj;

        } else if (condition.hasOwnProperty("budgetPrice") && !condition.hasOwnProperty("bedrooms")) {
            var budgetPrice = condition.budgetPrice.split(",");
            var minRange = budgetPrice[0];
            var maxRange = budgetPrice[1];

             subCondition[dbId]=condition.id;
            andCondition.push(subCondition,Sequelize.literal("`hp_unit_details.hp_unit_prices`.`price_per_sqft` * `hp_unit_details`.`property_size`  BETWEEN " + minRange + " AND " + maxRange))
               obj['$and']=andCondition;

            return obj;

        }

           obj[dbId] =condition.id

        return  obj;
      }

Upvotes: 0

Daphoque
Daphoque

Reputation: 4678

Split in function and store conditions and function pointer in an array

var conditions = [
  {
      keys: [
          {"key": "id", required:true}
          {"key": "price", required:false}
      ],
      function: fn1
  },
  {
      keys: [
            {"key": "id", required:false}
            {"key": "price", required:false}
      ],
      function: fn2
  }
];

function checkKey(obj, id, required)
{
    if(required)
      return obj.hasOwnProperty(id);
    else
      return !obj.hasOwnProperty(id);
}

function checkKeys(obj, keys)
{
   var condition = true;
   for(var i = 0; i < keys.length; i++)
   {
      condition &= checkKey(obj, keys[i].key, keys[i].required);
   }
   return condition;
}

for(var i = 0; i < conditions.length; i++)
{
   if(checkKeys(obj, conditions[i].keys))
      return conditions[i].function(obj);
}

Upvotes: 1

Related Questions