Skip to content

Takes a tree of operators and operands and calculates its value.

License

Notifications You must be signed in to change notification settings

dancrumb/operation-tree

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Operation Tree

npm package

license github-issues Build Status Code Climate Test Coverage

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.

Install

npm install operation-tree

Usage

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;

Caveats

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.

Author

Dan Rumney dancrumb@gmail.com https://github.com/dancrumb

License

Contributing

Contributions are highly welcome!

About

Takes a tree of operators and operands and calculates its value.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published