pvyas96's picture
Upload 20 files
c235ef4 verified
import React, { useState } from 'react';
const Calculator: React.FC = () => {
const [display, setDisplay] = useState('0');
const [expression, setExpression] = useState('');
const handleButtonClick = (value: string) => {
if (value === 'C') {
setDisplay('0');
setExpression('');
} else if (value === '=') {
try {
// WARNING: eval() is used for simplicity. In a production app, a safer math expression parser is recommended.
const result = eval(expression.replace(/%/g, '/100'));
setDisplay(String(result));
setExpression(String(result));
} catch (error) {
setDisplay('Error');
setExpression('');
}
} else if (value === 'del') {
setExpression(prev => prev.slice(0, -1));
setDisplay(prev => prev.slice(0, -1) || '0');
} else if (['sin', 'cos', 'tan', 'log'].includes(value)) {
try {
const num = parseFloat(expression);
if (isNaN(num)) throw new Error();
let result;
if(value === 'sin') result = Math.sin(num * Math.PI / 180);
if(value === 'cos') result = Math.cos(num * Math.PI / 180);
if(value === 'tan') result = Math.tan(num * Math.PI / 180);
if(value === 'log') result = Math.log10(num);
setDisplay(String(result));
setExpression(String(result));
} catch {
setDisplay('Error');
setExpression('');
}
} else {
if (display === '0' || display === 'Error') {
setDisplay(value);
setExpression(value);
} else {
setDisplay(prev => prev + value);
setExpression(prev => prev + value);
}
}
};
const buttons = [
'sin', 'cos', 'tan', 'log',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '%', '+',
'C', 'del', '=',
];
return (
<div className="bg-white dark:bg-gray-800/80 rounded-lg shadow-lg p-4 border border-gray-200 dark:border-gray-700">
<h3 className="font-bold text-xl text-gray-800 dark:text-gray-100 mb-2">Calculator</h3>
<div className="bg-gray-200 dark:bg-gray-900 text-gray-900 dark:text-gray-200 text-right p-2 rounded-md mb-4 text-3xl font-mono break-words h-16 flex items-center justify-end">{display}</div>
<div className="grid grid-cols-4 gap-2">
{buttons.map(btn => (
<button
key={btn}
onClick={() => handleButtonClick(btn)}
className={`p-3 rounded-md text-xl font-semibold transition ${
'/*-+='.includes(btn) ? 'bg-blue-500 text-white hover:bg-blue-600' :
btn === 'C' || btn === 'del' ? 'bg-red-500 text-white hover:bg-red-600' :
'bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-100 hover:bg-gray-300 dark:hover:bg-gray-500'
} ${btn === '=' && 'col-span-2'}`}
>
{btn}
</button>
))}
</div>
</div>
);
};
export default Calculator;