JSFiddle - React, Tailwind, and code Playground

by Evgeniy Lukovsky

HTML

<input class="first-operand" type="text">
<input class="second-operand" type="text">
<button class="plus-op">+</button>
<button class="sub-op">-</button>
<button class="mul-op">*</button>
<button class="div-op">/</button>
<input class="output" type="text" disabled="disabled">

TypeScript

class Calc {
  constructor() {
    this.firstInput = document.querySelector(".first-operand");
    this.secondInput = document.querySelector(".second-operand");
    this.output = document.querySelector(".output");
    this.plusOp = document.querySelector(".plus-op");
    this.subOp = document.querySelector(".sub-op");
    this.mulOp = document.querySelector(".mul-op");
    this.divOp = document.querySelector(".div-op");

    // Use arrow functions for event listeners to maintain 'this' context
    this.plusOp.addEventListener('click', () => this.handleOperation(this.plusHandler));
    this.subOp.addEventListener('click', () => this.handleOperation(this.subHandler));
    this.mulOp.addEventListener('click', () => this.handleOperation(this.mulHandler));
    this.divOp.addEventListener('click', () => this.handleOperation(this.divHandler));
  }

  // General method to handle operations and report errors
  handleOperation(handlerFunction) {
    try {
      this.clearOutput(); // Clear any previous errors
      this.checkNotEmpty();
      handlerFunction.call(this); // Execute the specific handler function
    } catch (error) {
      this.reportError(error.message); // Report errors in the output
    }
  }

  // Clear the output field
  clearOutput() {
    this.output.value = '';
  }

  // Report errors in the output
  reportError(errorMessage) {
    this.output.value = errorMessage;
  }

  // Check if input fields are not empty and contain valid numbers
  checkNotEmpty() {
    if (this.firstInput.value.trim() === '' || this.secondInput.value.trim() === '') {
      throw new Error("Please enter values in both fields");
    }

    for (let num of [this.firstInput.value, this.secondInput.value]) {
      let number = parseFloat(num);
      if (isNaN(number)) {
        throw new Error("Invalid input. Please enter valid numbers");
      }
    }
  }

  // Perform addition operation
  plusHandler() {
    let output = parseFloat(this.firstInput.value) +...