JSFiddle - React, Tailwind, and code Playground

by Robert Mochel

HTML

<div id="wrapped">
  <h1>Assignment 12</h1>
  <h4>Enter 2 numbers for x and y and click "Calculate" or hit the "enter" key to solve the expression.</h4>
  <input type="input" id="inputx" placeholder="Input X" onkeypress="handle(event)">
  <input type="input" id="inputy" placeholder="Input Y" onkeypress="handle(event)">
  <br>
  <br>
  <input type="button" value="Calculate" id="bt1" onClick="limitInput();">
  <h2 id="evaluate">3 * (X + 5 * Y) = ?</h2>

</div>

CSS

#wrapped {
  font-family: Verdana, Geneva, sans-serif;
  background: #FCF75C;
  border-radius: 25px;
  border: 5px solid #7AB5F0;
  padding: 20px;
  width: 500px;
  height: 100%;
}

#bt1 {
  font-family: Verdana, Geneva, sans-serif;
  background: #d4fcfb;
  border-radius: 25px;
  border: 2px solid #92e881;
  padding: 5px;
  width: 123px;
  height: 100%;
}

#inputx,
#inputy {
  font-family: Verdana, Geneva, sans-serif;
  background: #d4fcfb;
  border-radius: 25px;
  border: 2px solid #92e881;
  padding: 5px;
  width: 55px;
  height: 100%;
}

JavaScript

//Assignment 12

function handle(e) {
  var key = e.keyCode || e.which;
  if (key == 13) {
    limitInput();
  }
}
var Node = function(v, l, r) {
  this.value = v;
  this.left = l;
  this.right = r;
}

function calculate(left, right, op) {
  if (op == '+') {
    return parseInt(left) + parseInt(right);
  } else if (op == '-') {
    return parseInt(left) - parseInt(right);
  } else if (op == '*') {
    return parseInt(left) * parseInt(right);
  } else {
    return parseInt(left) + parseInt(right);
  }
}

function isInteger(number) {
  return (number % 1 === 0);
}

function evaluate(n) {
  if (n) {
    if (isInteger(n)) {
      return n;
    } else {
      var left = evaluate(n.left);
      var right = evaluate(n.right);
      var op = n.value;
      return calculate(left, right, op);
    }
  }
}

function limitInput() {
  var x = document.getElementById("inputx").value;
  var y = document.getElementById("inputy").value;
  if (x === '') {
    alert("Please enter an integer for X");
  }
  if (y === '') {
    alert("Please enter an integer for Y");
  } else if (!isInteger(x) || !isInteger(y)) {
    alert("Please enter only Integers. <br>You entered: " + x + " for x & " + y + " for y");
  } else {
    var binaryTree = new Node('*', 3, new Node('+', new Node('*', 5, y), x));
    document.getElementById("evaluate").innerHTML = "3 * (" + x + " + 5 * " + y + ")= " + evaluate(binaryTree).toString();
  }
}