//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();
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.