Guest User

Untitled

a guest
Oct 8th, 2019
518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     const keys = Array.from(document.getElementsByClassName('keys'));
  3.     const expressionOutput = document.getElementById('expressionOutput');
  4.     const result = document.getElementById('result');
  5.     const clearButton = document.querySelector('.clear');
  6.     let operand;
  7.     let firstNumber = '';
  8.     let secondNumber = '';
  9.  
  10.     const calculator = {
  11.         '+': (a, b) => a + b,
  12.         '-': (a, b) => a - b,
  13.         '*': (a, b) => a * b,
  14.         '/': (a, b) => a / b
  15.     }
  16.  
  17.     keys.map(key => key.addEventListener('click', function (evt) {
  18.         const currentSelection = evt.target.value;
  19.  
  20.         clearButton.addEventListener('click', () => {
  21.             expressionOutput.textContent = '';
  22.             result.textContent = '';
  23.             firstNumber = '';
  24.             secondNumber = '';
  25.             operand = '';
  26.         })
  27.  
  28.         if (+currentSelection || currentSelection == '.' || currentSelection == '0') {
  29.             if (!operand) {
  30.                 firstNumber += currentSelection;
  31.                 expressionOutput.textContent += currentSelection;
  32.             } else {
  33.                 secondNumber += currentSelection;
  34.                 expressionOutput.textContent += currentSelection
  35.             }
  36.         } else if (calculator.hasOwnProperty(currentSelection)) {
  37.             operand = currentSelection;
  38.             expressionOutput.textContent += ` ${operand} `;
  39.         } else if (currentSelection == '=') {
  40.             if (+firstNumber && +secondNumber) { //check if both are valid nums
  41.                 result.textContent = calculator[operand](+firstNumber, +secondNumber);
  42.             } else {
  43.                 result.textContent = 'NaN';
  44.             }
  45.         }
  46.     }))
  47. }
Add Comment
Please, Sign In to add comment