diff --git a/src/components/apps/Calculator/Calculator.svelte b/src/components/apps/Calculator/Calculator.svelte index ffbc763c..d0492421 100644 --- a/src/components/apps/Calculator/Calculator.svelte +++ b/src/components/apps/Calculator/Calculator.svelte @@ -5,43 +5,124 @@ import PlusMinus from '~icons/majesticons/plus-minus-2'; import Division from '~icons/ph/divide-bold'; import Multiply from '~icons/uil/multiply'; + + // Calculator state + let display = '0'; + let firstOperand: number | null = null; + let operator: string | null = null; + let waitingForSecondOperand = false; + + function inputDigit(digit: string) { + if (waitingForSecondOperand) { + display = digit; + waitingForSecondOperand = false; + } else { + display = display === '0' ? digit : display + digit; + } + } + + function inputDecimal() { + if (waitingForSecondOperand) { + display = '0.'; + waitingForSecondOperand = false; + return; + } + if (!display.includes('.')) { + display += '.'; + } + } + + function clearAll() { + display = '0'; + firstOperand = null; + operator = null; + waitingForSecondOperand = false; + } + + function handleOperator(nextOperator: string) { + const inputValue = parseFloat(display); + if (operator && waitingForSecondOperand) { + operator = nextOperator; + return; + } + if (firstOperand == null) { + firstOperand = inputValue; + } else if (operator) { + const result = performCalculation(operator, firstOperand, inputValue); + display = String(result); + firstOperand = result; + } + operator = nextOperator; + waitingForSecondOperand = true; + } + + function performCalculation(op: string, a: number, b: number) { + switch (op) { + case '+': return a + b; + case '-': return a - b; + case '×': return a * b; + case '÷': return b !== 0 ? a / b : 'Error'; + default: return b; + } + } + + function handleEquals() { + if (operator && firstOperand != null && !waitingForSecondOperand) { + const inputValue = parseFloat(display); + const result = performCalculation(operator, firstOperand, inputValue); + display = String(result); + firstOperand = null; + operator = null; + waitingForSecondOperand = false; + } + } + + function handlePlusMinus() { + if (display !== '0') { + display = display.startsWith('-') ? display.slice(1) : '-' + display; + } + } + + function handlePercent() { + display = String(parseFloat(display) / 100); + }
-
0
+
{display}
- - + - - + - - - - + + + - - - - + + + - - - - - + + + + - - + +