Graduate Assignment #1

Proving Understanding

by Philippe Xantus

HTML

<h1>Graduate Assignment #1</h1>
<h2>Proving My Understanding</h2>
<p>I've designed a simple calculator that demonstrates an understanding of Week 3-6:
<ul>
  <li>Basic data types, variables, objects and mathematical operations</li>
  <li>Tests, Lists, and Loops</li>
  <li>Functions and Objects</li>
</ul></p>
<p>Please see the comments for explanation!</p>
<hr>
<p>Add, subtract, multiply, or divide two numbers:</p>
<input id="inputField"></input>
<p>The answer is: <span id="result"></span></p>

JavaScript

//design a simple calculator that does one operation on two numbers.
//only acceptable operators are numbers and + - / *

//WEEK 5: FUNCTIONS AS VARIABLES!
var inputField = document.getElementById("inputField");
//onchange means that every time the value in the input box changes, this function will run
//WEEK 6: ASSIGNING A FUNCTION AS A VARIABLE!
inputField.onchange = function() {
  document.getElementById("result").innerHTML = calc(inputField.value)
}


function calc(entry) {
  //operators array containing the only acceptable operators
  //WEEK 4: ARRAYS!
  ops = "+-/*";
  //WEEK 4: LOOPING!
  //for loop iterating over valid operators
  for (i = 0; i < ops.length; i++) {
    //create new variable for array of the arguments
    //and find arguments array values by splitting at the i of operator
    var args = entry.split(ops[i]);
    //WEEK 4: BASIC CONDITIONALS!
    //if the number of arguments values equals 2, then the i of operator
    //is equal to the operator in the entry
    if (args.length == 2) {
      //check to see if the operator in the entry is a "+"
      if (ops[i] == "+") {
      	//WEEK 3: MATHEMATICAL OPERATIONS!
        //WEEK 3: TYPE COERCION!
        //do the math
        //don't forget to check the i of args for numbers
        var answer = parseFloat(args[0]) + parseFloat(args[1]);
        if (isNaN(answer)) {
          var answer = "Beep boop. Something's wrong. Try again!";
          return answer;
        } else if (!isNaN(answer)) {
          return answer;
        }
      }
      //check to see if the operator in the entry is a "-"
      else if (ops[i] == "-") {
        //do the math
        //don't forget to check the i of args for numbers
        var answer = parseFloat(args[0]) - parseFloat(args[1]);
        if (isNaN(answer)) {
          var answer = "Beep boop. Something's wrong. Try again!";
          return answer;
        } else if (!isNaN(answer)) {
          return answer;
        }

      }
      //check to see if the...