How can I create a compiler that can evaluate logical operators and operands specified on an object, similar to MongoDB's $or and $and operators? For example:
return {
$or: [
foo: [...],
bar: [...]
]
}
The compiler would call corresponding functions for each operand like foo
and bar
, then apply logical OR to the results. It should be able to handle nested logical operators as well. An example of a complex operation:
return {
$or: [
{
$and: [
{ foo: [...] },
{ bar: [...] }
]
},
{ baz: [...] },
() => m < n
]
}
A simplified definition of the functions for foo, bar
, and baz
:
export const evalFoo = items => {
return items.indexOf("foo") >= 0;
};
export const evalBar = items => {
return items.indexOf("bar") >= 0;
};
export const evalBaz = items => {
return items.indexOf("baz") >= 0;
};
Sample data:
Set 1
m = 4; n = 1; foo: ['foo', 'x']; bar: ['bar', 'y']; baz: ['baz', 'z']
RESULT = true; // because $and results to true.
Set 2
m = 4; n = 1; foo: ['x']; bar: ['y']; baz: ['x']
RESULT = false; // because m > n and $and results to false.
Set 3
m = 1; n = 3; foo: ['x']; bar: ['y']; baz: ['x']
RESULT = true; // because m < n.
Set 4
m = 3; n = 1; foo: ['x']; bar: ['bar']; baz: ['z']
RESULT = true; // because m > n, baz() is false and x and $and is false.