Skip to content

Instantly share code, notes, and snippets.

@marrionluaka
Last active May 2, 2017 22:56
Show Gist options
  • Save marrionluaka/e631cb7324a4dea5fd4d2f2051292f7c to your computer and use it in GitHub Desktop.
Save marrionluaka/e631cb7324a4dea5fd4d2f2051292f7c to your computer and use it in GitHub Desktop.
Abstract Syntax Tree (JavaScript)
var Node = (function(){
return function _Node(operation, value, leftChild, rightChild){
this.operation = operation;
this.value = value;
this.leftChild = leftChild;
this.rightChild = rightChild;
};
}());
function evaluate(node){
if(node.value !== null){
return node.value;
}
switch(node.operation){
case "+": return evaluate(node.leftChild) + evaluate(node.rightChild);
case "-": return evaluate(node.leftChild) - evaluate(node.rightChild);
case "*": return evaluate(node.leftChild) * evaluate(node.rightChild);
case "/": return evaluate(node.leftChild) / evaluate(node.rightChild);
}
return 0;
}
//Eval 5 + ( 25 * 6 )
/*
+
/ \
* 5
/ \
25 6
*/
// Create Nodes
var sixNode = new Node(null, 6, null, null);
var fiveNode = new Node(null, 5, null, null);
var twentyFiveNode = new Node(null, 25, null, null);
var mult25_6Node = new Node("*", null, twentyFiveNode, sixNode);
var rootPlusNode = new Node("+", null, mult25_6Node, fiveNode);
// Usage
evaluate(rootPlusNode); // -> 155
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment