Florent Descroix Florent Descroix - 4 months ago 7
Javascript Question

Dynamic generated condition JS

I'm looking for the best way to make dynamic generated condition inside a loop.

A sample worth 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 use the
eval()
function, which works well but that is REALLY too slow ! For a 200 elements array, this code take 25ms to be executed !
This is really not acceptable, knowing that I'm going to use this kind of thing on arrays with thousands of elements.

Have you got an idea to do that another way, faster ?

Answer

Create a new Function(), 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);
    }
}
Comments