JSFiddle - React, Tailwind, and code Playground

by Ryan Brown

HTML

<h1>Module 4 Assignment 1</h1>
<div id="form-array">    
  <form>
      Enter a number or operator ( "*" "/" "+" "-"):<br><br>
          <input type="text" name="input" id="input" value="7"><br><br>
  </form>       
  <input type="submit" id="click" value="Enter"><br><br>
</div>
<div id="result"></div>

CSS

#click {
    font-size: inherit;
    color: #FFF;
    background-color: #000;
    width: 10em;  
    height: 3em;
}

JavaScript

//when 'Enter' is clicked call myFormSubmit function
document.getElementById("click").onclick = function() {myFormSubmit()};
array = new Array();
function myFormSubmit() {
  var reg = /^\d*\.?\d*$/; //check for decimal or whole number with regular expression
  var input = document.getElementById("input").value;
  
  switch (input) {
    case "*":
    case "/":
    case "+":
    case "-":
      operation(input);
      break;
    default:
    if (reg.test(input) == true){
      array.unshift(parseFloat(input));
    }
    else {
      return document.getElementById('result').innerHTML = "Sorry, " + input + " is not accepted. Please enter a number.";
    }   
  }    document.getElementById('result').innerHTML = array.join("<br>"); 
}

function operation(input) {
  if (array.length >= 2) {
    switch (input) {
      case "*":
        array.unshift(array[0] * array[1]);
        break;
      case "/"://unshift if result is not NaN or infinity
      if (isNaN(array[0] / array[1]) == false && 
          isFinite(array[0] / array[1]) == true) array.unshift(array[0] / array[1]);
        break;
      case "+":
        array.unshift(array[0] + array[1]);
        break;
      case "-":
        array.unshift(array[0] - array[1]);
        break;
    }
    array.splice(1,2); //(index, how many)
  }
  else {
    alert("Please enter at least two numbers before entering an operator.");
  }
}
/*
Submission3 Module4 Assignment1

Assignment 1 - Implement a Stack computer in Javascript (you will turn in a link to your program in JSFiddle). This is a simple computer that keeps a stack, when a number is entered it goes onto the top of the stack. When an operation is entered, the previous 2 numbers are operated on by the operation.
 
For example
2 [enter]   2
5 [enter]   5 2
*  [enter]  * 5 2 -> collapses to 10
 
would leave at 10 at the top of the stack.
 
The program should use a simple input box, either a text field or prompt and display the contents of the Stack.
 
Quizzes (Quiz...