Instead of relying on string manipulation, I propose an alternative solution that involves combining functions. By using function composition to build code rather than manipulating strings, the approach is likely to be less error-prone and more professional.
In Javascript, you have the ability to work with first-order functions, meaning you can easily pass around and combine predicates - functions that return a boolean value. For instance:
var isLabelTest = function(obj) {
return obj.label === 'test';
}
Rather than storing conditions as strings, consider storing them as predicate functions instead. You can then create functions that take predicates and produce new predicates:
var binaryAnd = function(predA, predB) {
return function(obj) {
return predA(obj) && predB(obj);
};
};
var binaryOr = function(predA, predB) {
return function(obj) {
return predA(obj) || predB(obj);
};
};
You can also develop functions that take an array of predicates and merge them into a single new predicate:
var and = function(preds) {
return preds.reduce(binaryAnd, function(obj) {return true;});
};
var or = function(preds) {
return preds.reduce(binaryOr, function(obj) {return false;});
};
With an "andArray" containing predicates that must all evaluate to true
, and an "orArray" with predicates where at least one needs to be true
, the following code accomplishes the task:
var results = [];
var combinedPredicate = binaryAnd(and(andArray), or(orArray));
var pushIfCondition = function (obj) {
results.push(combinedPredicate(obj));
};
dataArray.forEach(pushIfCondition);
Lastly, remember that writing your own functions for combining predicates is not mandatory - libraries like ramda offer more efficient implementations.