So, sometimes, when you're working on a design, you end up with a tree representation of a series of operations.
For instance, the expression A || B || (C && D)
might be represented
as:
or | + - A | + - B | + - and | + - C | + - D
From this graphical representation, we can make an array representation:
[ 'or', ['A', 'B', 'and', ['C', 'D']]]
This module provides a method resolve
, which takes a tree array and resolves
it to a final value.
npm install operation-tree
To keep things simple, operators are kept out of the tree. Values can also be kept out of the tree, if desired. As such, you need to pass in a map of operator and operand values. Any values that are not in the map can be placed in the tree explicitly. For the tree above, you might use:
var tree = [ 'or', ['A', 'B', 'and', ['C', 'D']]];
var operators = {
'and': function (a, b) {
return a && b;
},
'or': function (a, b) {
return a || b;
}
};
var vals = {
'A': true,
'B': false,
'C': false,
'D': true
};
operationTree.resolve(tree, operators, values) === false;
Operator functions must explicitly declare their parameters, since that's the only way for this module to determine if they are binary or unary operators.
Dan Rumney dancrumb@gmail.com https://github.com/dancrumb
Contributions are highly welcome!