Skip to main content

calculator

Certainly! We can create a number pad for the calculator by mapping an array of numbers to generate the buttons dynamically. Here's the updated code for the Calculator component with the number buttons mapped from an array:

import React, { useState } from 'react';

type Operation = 'add' | 'subtract' | 'multiply' | 'divide';

const CalculatorApp: React.FC = () => {
const [input, setInput] = useState<string>('0');
const [previousInput, setPreviousInput] = useState<string>('0');
const [operation, setOperation] = useState<Operation | null>(null);

const handleNumberClick = (number: string) => {
setInput((currentInput) => (currentInput === '0' ? number : currentInput + number));
};

const handleOperationClick = (nextOperation: Operation) => {
setOperation(nextOperation);
setPreviousInput(input);
setInput('0');
};

const calculateResult = () => {
const numCurrent = parseFloat(input);
const numPrevious = parseFloat(previousInput);

let result = 0;

switch (operation) {
case 'add':
result = numPrevious + numCurrent;
break;
case 'subtract':
result = numPrevious - numCurrent;
break;
case 'multiply':
result = numPrevious * numCurrent;
break;
case 'divide':
result = numPrevious / numCurrent;
break;
default:
return;
}

setInput(String(result));
setOperation(null);
setPreviousInput('0');
};

const handleClear = () => {
setInput('0');
setPreviousInput('0');
setOperation(null);
};

// Array of numbers for our calculator
const numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];

return (
<div>
<div>Input: {input}</div>
<div>
{numbers.map((number) => (
<button key={number} onClick={() => handleNumberClick(number)}>
{number}
</button>
))}
<button onClick={() => handleOperationClick('add')}>+</button>
<button onClick={() => handleOperationClick('subtract')}>-</button>
<button onClick={() => handleOperationClick('multiply')}>*</button>
<button onClick={() => handleOperationClick('divide')}>/</button>
<button onClick={calculateResult}>=</button>
<button onClick={handleClear}>C</button>
</div>
</div>
);
};

export default CalculatorApp;

In this updated version of the Calculator component, instead of manually creating each button for the numbers, we map through the numbers array to create a button for each number. This helps to keep our code DRY (Don't Repeat Yourself) and easier to manage, especially if we decide to change the layout or style of the number buttons in the future.