diff --git a/frontend/src/pages/calculator.tsx b/frontend/src/pages/calculator.tsx index 9a2e9d2..e723421 100644 --- a/frontend/src/pages/calculator.tsx +++ b/frontend/src/pages/calculator.tsx @@ -1,4 +1,4 @@ -import { mdiCalculator, mdiHistory } from '@mdi/js' +import { mdiCalculator } from '@mdi/js' import Head from 'next/head' import React, { useState, ReactElement } from 'react' import CardBox from '../components/CardBox' @@ -11,23 +11,37 @@ import BaseButtons from '../components/BaseButtons' import FormField from '../components/FormField' const CalculatorPage = () => { - const [input, setInput] = useState('') - const [results, setResults] = useState({ hex: '', dec: '', oct: '', bin: '' }) + const [val1, setVal1] = useState('') + const [val2, setVal2] = useState('') + const [base, setBase] = useState<'hex' | 'dec' | 'oct' | 'bin'>('dec') + const [operation, setOperation] = useState<'+' | '-' | '*' | '/' | 'AND' | 'OR' | 'XOR'>('+') + const [result, setResult] = useState(null) + + const parseInput = (val: string, base: number) => parseInt(val, base) const handleCalculate = () => { - // Basic implementation for now - this should ideally call the backend try { - const decValue = parseInt(input, 10) - if (isNaN(decValue)) throw new Error('Invalid input') + const baseMap = { hex: 16, dec: 10, oct: 8, bin: 2 } + const v1 = parseInput(val1, baseMap[base]) + const v2 = parseInput(val2, baseMap[base]) - setResults({ - hex: decValue.toString(16).toUpperCase(), - dec: decValue.toString(10), - oct: decValue.toString(8), - bin: decValue.toString(2) - }) + 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 + } + + setResult(res.toString(baseMap[base]).toUpperCase()) } catch (e) { - alert('Error: Please enter a valid decimal number') + alert('Error: Invalid operation') } } @@ -41,28 +55,29 @@ const CalculatorPage = () => { {''} - - setInput(e.target.value)} - className="w-full p-2 border rounded" - placeholder="e.g. 255" - /> - +
+ {(['hex', 'dec', 'oct', 'bin'] as const).map(b => ( + setBase(b)} /> + ))} +
+
+ setVal1(e.target.value)} className="w-full p-2 border rounded" /> + + + + setVal2(e.target.value)} className="w-full p-2 border rounded" /> +
- {results.dec && ( + {result !== null && ( -
-
Decimal: {results.dec}
-
Hex: 0x{results.hex}
-
Octal: {results.oct}
-
Binary: {results.bin}
-
+
Result: {result}
)} @@ -70,8 +85,6 @@ const CalculatorPage = () => { ) } -CalculatorPage.getLayout = function getLayout(page: ReactElement) { - return {page} -} +CalculatorPage.getLayout = (page: ReactElement) => {page} export default CalculatorPage