expr-eval icon indicating copy to clipboard operation
expr-eval copied to clipboard

Integer and string comparison

Open Pavithra-Ravichandran opened this issue 8 years ago • 2 comments

var Parser = require('expr-eval').Parser;

var parser = new Parser(); var expr = parser.parse('x > 1'); console.log(expr.evaluate({ x: "3" })); //expected: true && actual: true expr = parser.parse('y == 3'); console.log(expr.evaluate({ y: "3" })); //expected: true && actual: false

When string and integer are compared with Greater than or less than returns the expected output, but the equals operator does not return as expected.

Pavithra-Ravichandran avatar Sep 21 '17 10:09 Pavithra-Ravichandran

Can you do expr = parser.parse('Number(y) == 3');

I think its by design that == performs a === check instead.

pbarbiero avatar Sep 21 '17 16:09 pbarbiero

@pbarbiero is correct, the == operator is using javascript's === operator by design. >, <, etc. work across types because it's simpler and I believe support for strings was added later, after they were implemented. The inconsistency obviously isn't ideal, and should probably be cleaned up eventually.

As far as @pbarbiero's suggestion to use Number, that's actually not exposed to expressions, but you can use the prefix + operator to coerce a string to a number. So this should do what you're expecting:

var Parser = require('expr-eval').Parser;

var parser = new Parser();
var expr = parser.parse('x > 1');
console.log(expr.evaluate({ x: "3" })); //expected: true && actual: true
expr = parser.parse('+y == 3');
console.log(expr.evaluate({ y: "3" })); //expected: true && actual: true

silentmatt avatar Sep 22 '17 15:09 silentmatt