JS dynamically generated condition

I am looking for the best way to make a dynamically generated condition inside a loop.

A sample is worth a thousand words, so here is my code:

var condition = "data.label == 'Test'";

for (var key in andArray) {
    condition += "&& " + andArray[key];
}

for (var key in orArray) {
    condition += "|| " + orArray[key];
}

var length = dataArray.length;
var result = [];
for (var i = 0; i < length; i++) {
    var data = dataArray[i];
    if (eval(condition)) {
        result.push(obj);
    }
}

I am using a function eval()that works well, but it is REALLY too slow! For an array of 200 elements, this code takes 25 ms! This is really unacceptable, knowing that I am going to use such things on arrays with thousands of elements.

Do you have an idea to do it differently, faster?

+4
source share
2 answers

Create new Function()in this way the string will be parsed only once:

var length = dataArray.length;
var result = [];
var fn = new Function('data', 'return ' + whereCondition);

for (var i = 0; i < length; i++) {
    var data = dataArray[i];
    if (fn(data)) {
        result.push(obj);
    }
}
+2
source

. . , , - , , "" ( ...).

Javascript , ( ) . - , . :

var isLabelTest = function(obj) {
  return obj.label === 'test';
}

.
, :

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);
  };
};

, :

var and = function(preds) {
  return preds.reduce(binaryAnd, function(obj) {return true;});
};

var or = function(preds) {
  return preds.reduce(binaryOr, function(obj) {return false;});
};

, "andArray" , true, "orArray" , true, :

var results = [];
var combinedPredicate = binaryAnd(and(andArray), or(orArray));
var pushIfCondition = function (obj) {
  results.push(combinedPredicate(obj));
};
dataArray.forEach(pushIfCondition);

, , , , ramda, .

+1

Source: https://habr.com/ru/post/1649812/


All Articles