JSFiddle - React, Tailwind, and code Playground
by Ryan Brown
HTML
<h1>Module 10</h1>
<form>
Enter x value.<br>
<input type="text" id="x-value"><br>
Enter y value.<br>
<input type="text" id="y-value"><br>
<input type="button" value="Enter" id="click">
</form>
<div id="output"></div>
CSS
#click {
background-color: blue;
color: white;
margin-top: 8px;
margin-bottom: 8px;
width: 10em;
}
JavaScript
var key=0; var array=[]; var errors=[]; var result, total, x, y;
document.getElementById("click").onclick = function() {myFormSubmit()};
function myFormSubmit() {
array=[], errors=[];//reset
x = document.getElementById("x-value").value;
y = document.getElementById("y-value").value;
try {
if (x == "") throw "You didn't enter a x value.";
if (isNaN(x)) throw "Enter a numeric value for x. You entered " + x;
x = parseInt(x);
}
catch(err) {
errors.push(err);
}
try {
if (y == "") throw "You didn't enter a y value.";
if (isNaN(y)) throw "Enter a numeric value for y. You entered " + y;
y = parseInt(y);
}
catch(err) {
errors.push(err);
}
document.getElementById('output').innerHTML = errors.join("<br>");
if (errors.length == 0) {
var tree = new BinarySearchTree();
tree.insert( 3);
tree.insert( "*");
tree.insert( "(");
tree.insert( x);
tree.insert( "+");
tree.insert( 5);
tree.insert( "*");
tree.insert( y);
tree.insert( ")");
tree.preOrderTraverse(calculate_expression);//when called uses callback of preOrderTraverse to return nodes in order they were entered into tree (tracked by node.key, then stores them into an array. once complete, call the values from the array with the execption of the operators. Instead of using switch statement to convert known operator value from string to operation, just place operator in palce as necessary.
}
}
function BinarySearchTree() {
var Node = function(key, value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
};
var root = null;
this.insert = function(value){
key++;
var newNode = new Node(key, value);
if (root === null) {
root = newNode;
}
else {
insertNode(root, newNode);
}
};
//Pre-order Traversal
this.preOrderTraverse = function(callback) {
preOrderTraverseNode(root, callback);
};
}
var insertNode =...