Search code examples
javascriptfilterdynamicconditional-statementsevaluation

Dynamic evaluation of conditions not using Eval()


I need to be able to evaluate (True/False) some conditions not using Eval method. I came across this awesome technique which suits my needs: https://stackoverflow.com/a/68822307/9481833

Now I am trying to implement something like a Like operator and found the test function. Tried to amend the example as per the below but no joy:

const conditionalArray = [
  { name: "fridge", condition: "like", value: "sam" },
];

const dataTofilter = [
  { line: "Blah", revene: 3, sale: 2, fridge: "samsung" },
];

const conditions = {
  'like': (x, y) => x.test(/y/),
};

const result = dataTofilter.filter(data => {
  for (const el of conditionalArray) {
    if (!conditions[el.condition](data[el.name], el.value)) {
      return false;
    }
  }
  return true;
});

console.log(result);

Error message is that 'test' is not a function. Perhaps I'll need to handle this case in the filter codeblock at the bottom and look for the 'like' operator and handle it there ?


Solution

  • Therefore you should use match. I also fixed your like function so it won't match /y/ the literal but rather y the variable. Note: it needs escaping for RegExp.

    const conditionalArray = [{
      name: "fridge",
      condition: "like",
      value: "sam"
    }, ];
    
    const dataTofilter = [{
      line: "Blah",
      revene: 3,
      sale: 2,
      fridge: "samsung"
    }, ];
    
    const conditions = {
      'like': (x, y) => x.match(new RegExp(y)),
    };
    
    const result = dataTofilter.filter(data => {
      for (const el of conditionalArray) {
        if (!conditions[el.condition](data[el.name], el.value)) {
          return false;
        }
      }
      return true;
    });
    
    console.log(result);