JSFiddle - React, Tailwind, and code Playground

by hesster92

HTML

Assignment 12
<br><br>
3 * (x + 5 * y)
<br><br>
X = <input type="textbox" id="x">
<br>
Y = <input type="textbox" id="y">
<br><br>
<input type="button" id="btnCalc" value="Calculate" onClick="Calculate()">
<br>
<p id="output1"></p>
<br>
<p id="output2"></p>

JavaScript

var TNode = function(_content, _left, _right) {
  this.content = _content;
  this.left = _left;
  this.right = _right;
}

TNode.prototype.traverse = function() {
  var left = this.left.traverse();
  var right = this.right.traverse();
  switch (this.content) {
    case "+":
      return (left + right);

    case "*":
      return (left * right);
    
    case "/":
    	return (left / right);

  }
}

TNode.prototype.print = function() {
  var node2 = this.printNode();
  if (this.left != null) {
    node2 += this.left.print();
  }
  if (this.right != null) {
    node2 += this.right.print();
  }
  return node2;
}

TNode.prototype.printNode = function() {
  var node1 = "Node: " + this.content;
  if (this.left != null) {
    node1 += " Left: " + this.left.content;
  }

  if (this.right != null) {
    node1 = node1 + " Right: " + this.right.content;
  }
  node1 += "<br>";

  return node1;
}

var TLeaf = function(_content) {
  this.content = _content;
}

TLeaf.prototype.traverse = function() {
  return this.content;
}

TLeaf.prototype.print = function() {
  var s = "";
  return s;
}

function Calculate() {
  clearDisplay();
  var x = parseFloat(document.getElementById("x").value);
  var y = parseFloat(document.getElementById("y").value);
  if (isNaN(x) || isNaN(y)) {
    document.getElementById("output1").innerHTML = "Enter a value for X and Y";
    return;
  }

  var nodeA = new TLeaf(3);
  var nodeX = new TLeaf(x);
  var nodeB = new TLeaf(5);
  var nodeY = new TLeaf(y);
  var mult1 = new TNode("*", nodeB, nodeY);
  var addition = new TNode("+", nodeX, mult1);
  var mult2 = new TNode("*", nodeA, addition);
  var result = mult2.traverse();


  document.getElementById("output1").innerHTML = "X = " + x + "<br>" + "Y = " + y + "<br>" + "Output:" + result;

  document.getElementById("output2").innerHTML = mult2.print();
}

function clearDisplay() {
  document.getElementById("output1").innerHTML = "";
  document.getElementById("output2").innerHTML = "";
}