programm a calculator in typescript

To program a calculator in TypeScript, you can follow the steps below:

  1. Create a new HTML file for the calculator interface.
  2. Add the necessary HTML and CSS code to create the calculator interface.
  3. Create a new TypeScript file for the calculator logic.
  4. Define a class that represents the calculator.
  5. Add methods to the class for performing calculation operations such as addition, subtraction, multiplication, and division.
  6. Add event listeners to the HTML buttons to call the corresponding methods in the calculator class.

Here's an example code:

HTML:

<div class="calculator">
  <div class="display">
    <input type="text" id="display" readonly>
  </div>
  <div class="buttons">
    <button id="clear">C</button>
    <button id="sign">+/-</button>
    <button id="percent">%</button>
    <button id="divide">/</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <button id="multiply">*</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="subtract">-</button>
    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="add">+</button>
    <button id="zero">0</button>
    <button id="decimal">.</button>
    <button id="equal">=</button>
  </div>
</div>
790 chars
27 lines

CSS:

.calculator {
  width: 300px;
  height: 380px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  font-size: 18px;
  font-weight: bold;
}

.display {
  width: 100%;
  height: 60px;
  margin-bottom: 10px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.display input[type=text] {
  width: 100%;
  height: 100%;
  border: none;
  text-align: right;
  font-size: 36px;
  font-weight: bold;
  padding-right: 10px;
}

.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

button {
  width: 100%;
  height: 60px;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
  outline: none;
}

button:hover {
  background-color: #f5f5f5;
}

button:active {
  background-color: #ccc;
  color: #fff;
}
780 chars
53 lines

TypeScript:

index.ts
class Calculator {
  private displayValue: string;
  private firstOperand: number | null;
  private waitingForSecondOperand: boolean;
  private operator: string | null;

  constructor() {
    this.displayValue = '0';
    this.firstOperand = null;
    this.waitingForSecondOperand = false;
    this.operator = null;
  }

  private updateDisplay(): void {
    const display = document.getElementById('display') as HTMLInputElement;
    display.value = this.displayValue;
  }

  private clear(): void {
    this.displayValue = '0';
    this.firstOperand = null;
    this.waitingForSecondOperand = false;
    this.operator = null;
    this.updateDisplay();
  }

  private inputDigit(digit: string): void {
    if (this.waitingForSecondOperand) {
      this.displayValue = digit;
      this.waitingForSecondOperand = false;
    } else {
      this.displayValue = this.displayValue === '0' ? digit : this.displayValue + digit;
    }
    this.updateDisplay();
  }

  private inputDecimal(): void {
    if (!this.displayValue.includes('.')) {
      this.displayValue += '.';
      this.updateDisplay();
    }
  }

  private toggleSign(): void {
    this.displayValue = Number.parseFloat(this.displayValue) === 0 ? '0' : (-1 * Number.parseFloat(this.displayValue)).toString();
    this.updateDisplay();
  }

  private inputPercent(): void {
    this.displayValue = (Number.parseFloat(this.displayValue) / 100).toString();
    this.updateDisplay();
  }

  private performOperation(nextOperator: string): void {
    const inputValue = Number.parseFloat(this.displayValue);
    if (this.operator && this.waitingForSecondOperand) {
      this.operator = nextOperator;
      return;
    }
    if (this.firstOperand == null) {
      this.firstOperand = inputValue;
    } else if (this.operator) {
      const result = this.calculate(this.firstOperand, inputValue, this.operator);
      this.displayValue = result.toString();
      this.firstOperand = result;
    }
    this.waitingForSecondOperand = true;
    this.operator = nextOperator;
  }

  private calculate(firstOperand: number, secondOperand: number, operator: string): number {
    switch (operator) {
      case '+':
        return firstOperand + secondOperand;
      case '-':
        return firstOperand - secondOperand;
      case '*':
        return firstOperand * secondOperand;
      case '/':
        return firstOperand / secondOperand;
      default:
        return secondOperand;
    }
  }

  public start(): void {
    const buttons = document.querySelectorAll('.buttons button');
    buttons.forEach(button => {
      button.addEventListener('click', () => {
        const { id } = button as HTMLButtonElement;
        switch (id) {
          case 'clear':
            this.clear();
            break;
          case 'sign':
            this.toggleSign();
            break;
          case 'percent':
            this.inputPercent();
            break;
          case 'decimal':
            this.inputDecimal();
            break;
          case 'add':
          case 'subtract':
          case 'multiply':
          case 'divide':
            this.performOperation(id);
            break;
          case 'equal':
            this.performOperation(null);
            break;
          default:
            if (/^\d$/.test(id)) {
              this.inputDigit(id);
            }
            break;
        }
      });
    });
  }
}

const calculator = new Calculator();
calculator.start();
3446 chars
126 lines

Finally, you can compile the TypeScript code to JavaScript using the following command in the terminal:

index.ts
tsc calculator.ts
18 chars
2 lines

This will generate a JavaScript file named calculator.js that you can include in your HTML file.

gistlibby LogSnag