0
\$\begingroup\$

I'm running a lot of functions to build a mongoDb request. Based on their response (if not falsy) I'm appending the return values to an array ruleConditions[] which is used later.

Currently I'm doing it this way:

//building ruleConditions
var ruleConditions = {$and: []};

var fromConditions = mongoRequestsHelper.getFromConditions(rule.from);
if (fromConditions) ruleConditions.$and.push(fromConditions);

//and 4 similar blocks

Is there any way to avoid unneeded variables creation (carTypesConditions...)?

Calling functions twice like:

if (mongoRequestsHelper.getFromConditions(rule.moversFilter)) ruleConditions.push(mongoRequestsHelper.getFromConditions(rule.moversFilter))

is not a good idea obviously.

\$\endgroup\$
  • \$\begingroup\$ if(getMoversConditions()) conditions.push(getMoversConditions()). Depending on how long it takes to run your functions, this is a bad approach performance-wise, though, because it requires your to call each function twice. \$\endgroup\$ – connexo Mar 18 '18 at 12:36
  • \$\begingroup\$ @connexo updated question before your proposal :) I know about running twice variant, not good for me. \$\endgroup\$ – Sol Mar 18 '18 at 12:42
  • 1
    \$\begingroup\$ Be aware that you are not checking for false, but for falsy. If a function returns either of 0, "", null or undefined, your condition will also omit that push. I'm saying that because I altered your question before and changed that to falsy - which you changed back to false. \$\endgroup\$ – connexo Mar 18 '18 at 12:45
3
\$\begingroup\$

First up, you should really be using more modern variable definitions (using let and const instead of var).

As for your conditional processing for the mongoDB clauses, the simpler way to process the data would be to accumulate all the clauses in to a single temporary array, and then filter that array in to the actual query clause. For example, consider:

const clauses = [
    mongoRequestsHelper.getFromConditions(rule.A),
    mongoRequestsHelper.getFromConditions(rule.B),
    mongoRequestsHelper.getFromConditions(rule.C),
    mongoRequestsHelper.getFromConditions(rule.D),
    ......
];

const ruleConditions = {
    // filter out non-truthy clauses
    $and: clauses.filter(clause => clause)
};
\$\endgroup\$
  • \$\begingroup\$ if I would have single condition, is it possible to do it in one line? Something like var type = options.carType || false, but instead of false do nothing? \$\endgroup\$ – Sol Mar 20 '18 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.