-1

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 ?

SteveP495
  • 13
  • 4

1 Answers1

0

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);
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Great thanks but out of interest why is 'test' not a possibility ? I looked to it as match is slower from reading I have done here and elsewhere – SteveP495 Sep 04 '22 at 08:09
  • `test()` is not a method of a `String` (as `x` is) but rather of `RegExp` – IT goldman Sep 04 '22 at 09:01
  • Ok thanks again. Learning a lot. By that logic, match is not a method of a string either, so why doesn't 'x.test(new RegExp(y))' work ? – SteveP495 Sep 04 '22 at 09:21
  • It is of [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) sorry for ambiguity – IT goldman Sep 04 '22 at 09:24
  • No worries thanks. All I need is a Boolean response to the condition being met. Is 'match' the only/fastest method to achieve this ? – SteveP495 Sep 04 '22 at 09:28
  • `String.prototype.includes` is faster https://stackoverflow.com/questions/5296268/fastest-way-to-check-a-string-contain-another-substring-in-javascript – IT goldman Sep 04 '22 at 10:15