Last active
May 2, 2017 22:56
-
-
Save marrionluaka/e631cb7324a4dea5fd4d2f2051292f7c to your computer and use it in GitHub Desktop.
Abstract Syntax Tree (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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