vadimkorr
3/20/2018 - 9:24 PM

parse-tree-and-solve

Parse tree and find result of expression'

const tree = {
    and: {
        left: {
            and: {
                left: {
                    le: {
                        left: {
                            fieldRef: "a.count"
                        },
                        right: {
                            integer: 18
                        }
                    }
                },
                right: {
                    gt: {
                        left: {
                            integer: 99
                        },
                        right: {
                            fieldRef: "a.count"
                        }
                    }
                }
            }
        },
        right: {
            eq: {
                left: {
                    fieldRef: 'a.thing'
                },
                right: {
                    boolean: false
                }
            }
        }
    }
}

let a = { thing: false, count: 18 };


function proc(data, tree) {
  let key = Object.keys(tree)[0];
  switch(key) {
      //OPERATIONS
    case 'and': {//AND
      let lOp = proc(data, tree[key].left);
      let rOp = proc(data, tree[key].right);
      return {
        res: lOp.res && rOp.res,
        exp: "(" + lOp.exp + " & " + rOp.exp + ")"
      }
    }
    case 'le': {//LESS OR EQ
      let lOp = proc(data, tree[key].left);
      let rOp = proc(data, tree[key].right);
      return {
        res: lOp.res <= rOp.res,
        exp: "(" + lOp.exp + " <= " + rOp.exp + ")"
      }
    }
    case 'gt': {//GRATER
      let lOp = proc(data, tree[key].left);
      let rOp = proc(data, tree[key].right);
      return {
        res: lOp.res > rOp.res,
        exp: "(" + lOp.exp + " > " + rOp.exp + ")"
      }
    }
    case 'eq': {//EQUAL
      let lOp = proc(data, tree[key].left);
      let rOp = proc(data, tree[key].right);
      return {
        res: lOp.res == rOp.res,
        exp: "(" + lOp.exp + " == " + rOp.exp + ")"
      }
    }	
      //VALUES
    case 'fieldRef': {//CUSTOM
      let val = data[tree[key].split('.')[1]];
      return {
        res: val,
        exp: val
      };
    }
    case 'integer': {//INTEGER
      let val = tree[key];
      return {
        res: val,
        exp: val
      };
    }
    case 'boolean': {//BOOLEAN
      let val = tree[key];
      return {
        res: val,
        exp: val
      };
    }
    default: {
      throw new Error("Unknown value " + key);
    }
  }
}

console.log(proc(a, tree))