8
This commit is contained in:
parent
0ba706f6b9
commit
f70acc8a33
@ -17,29 +17,36 @@ const CalculatorPage = () => {
|
||||
const [operation, setOperation] = useState<'+' | '-' | '*' | '/' | 'AND' | 'OR' | 'XOR'>('+')
|
||||
const [result, setResult] = useState<string | null>(null)
|
||||
const [activeInput, setActiveInput] = useState<'val1' | 'val2'>('val1')
|
||||
const [isSequential, setIsSequential] = useState(false)
|
||||
|
||||
const baseMap = { hex: 16, dec: 10, oct: 8, bin: 2 }
|
||||
|
||||
const calculate = (v1: string, v2: string, op: string) => {
|
||||
const num1 = parseInt(v1, baseMap[base])
|
||||
const num2 = parseInt(v2, baseMap[base])
|
||||
let res: number
|
||||
switch(op) {
|
||||
case '+': res = num1 + num2; break
|
||||
case '-': res = num1 - num2; break
|
||||
case '*': res = num1 * num2; break
|
||||
case '/': res = num1 / num2; break
|
||||
case 'AND': res = num1 & num2; break
|
||||
case 'OR': res = num1 | num2; break
|
||||
case 'XOR': res = num1 ^ num2; break
|
||||
default: res = num1
|
||||
}
|
||||
return res.toString(baseMap[base]).toUpperCase()
|
||||
}
|
||||
|
||||
const handleCalculate = () => {
|
||||
try {
|
||||
const v1 = parseInt(val1, baseMap[base])
|
||||
const v2 = parseInt(val2, baseMap[base])
|
||||
|
||||
if (isNaN(v1) || (val2 && isNaN(v2))) throw new Error('Invalid input')
|
||||
|
||||
let res: number
|
||||
switch(operation) {
|
||||
case '+': res = v1 + v2; break
|
||||
case '-': res = v1 - v2; break
|
||||
case '*': res = v1 * v2; break
|
||||
case '/': res = v1 / v2; break
|
||||
case 'AND': res = v1 & v2; break
|
||||
case 'OR': res = v1 | v2; break
|
||||
case 'XOR': res = v1 ^ v2; break
|
||||
default: res = v1
|
||||
const res = calculate(val1, val2, operation)
|
||||
setResult(res)
|
||||
if (isSequential) {
|
||||
setVal1(res)
|
||||
setVal2('')
|
||||
setActiveInput('val2')
|
||||
}
|
||||
|
||||
setResult(res.toString(baseMap[base]).toUpperCase())
|
||||
} catch (e) {
|
||||
alert('Error: Invalid calculation')
|
||||
}
|
||||
@ -72,6 +79,7 @@ const CalculatorPage = () => {
|
||||
{(['hex', 'dec', 'oct', 'bin'] as const).map(b => (
|
||||
<BaseButton key={b} color={base === b ? 'info' : 'light'} label={b.toUpperCase()} onClick={() => { setBase(b); setVal1(''); setVal2(''); setResult(null); }} />
|
||||
))}
|
||||
<BaseButton color={isSequential ? 'success' : 'light'} label="Sequential Mode" onClick={() => setIsSequential(!isSequential)} />
|
||||
</div>
|
||||
<div className="flex gap-4 mb-4">
|
||||
<div className="flex-1 cursor-pointer p-2 border-2 rounded" onClick={() => setActiveInput('val1')} style={{ borderColor: activeInput === 'val1' ? '#53F6C7' : '#ccc' }}>
|
||||
@ -114,4 +122,4 @@ const CalculatorPage = () => {
|
||||
|
||||
CalculatorPage.getLayout = (page: ReactElement) => <LayoutAuthenticated>{page}</LayoutAuthenticated>
|
||||
|
||||
export default CalculatorPage
|
||||
export default CalculatorPage
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user