2

I'm using Angular 7 and I want to evaluate an arithmetic function that I receive as string as follows:

I get a "value" from a service which is a number. I also get a "rule" to apply to this value as @Input parameter, which is a string and can contain ">", "<" and "==". Example:

value = 10;
rule = ">2"

I then want to apply that rule and check if it is true:

if (10 > 2) {
  console.log("this rule applies!");
}

I tried using eval like this:

const strValue: string = value.toString();
const expression = strValue.concat(rule);
if (eval(expression)) {
  console.log("this rule applies!");
}

But I'm getting an error:

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'".

So I guess I should not use "eval" to do this. Do you have any idea how I could solve it?

1
  • 2
    Are you confident that the data you will use eval on is safe? If so, then you can look for a way to enable this or otherwise bypass the unsafe-eval check because it's not unsafe. Otherwise, you need a different way of going about it. Commented May 17, 2019 at 6:27

2 Answers 2

3

You could use the regex (\D+)(\d+) to get any operator followed by a number. You could add more operators to the switch should you choose to extend it.

function evaluate(value, rule) {
  const [,operator, number] = rule.match(/(\D+)(\d+)/)
  
  switch(operator) {
    case ">" : return value > number
    case "<" : return value < number
    case "==" : return value == number
  }
  
  return null
}

console.log(evaluate(3, ">1"))
console.log(evaluate(3, "<2"))
console.log(evaluate(3, "==3"))

Sign up to request clarification or add additional context in comments.

Comments

2

You could get the operator and use a function for each operator.

function evaluate(value, rule) {
    const
        operators = {
            '<': (a, b) => a < b,
            '>': (a, b) => a > b,
            '==': (a, b) => a == b
        },
        [op, value2] = rule.match(/^(<|>|==)|.*$/g);

    return operators[op](value, value2);
}

console.log(evaluate(10, '<2'));
console.log(evaluate(10, '>2'));
console.log(evaluate(10, '==2'));
console.log(evaluate(10, '==10'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.