Skip to content
Permalink
630747de52
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
109 lines (97 sloc) 2.24 KB
const display = document.getElementById('result');
const buttons = document.querySelectorAll('button');
let currentValue = '';
let prevValue = '';
let operation = null;
let maxDigits = 10; // Maximum number of digits the calculator screen can display
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.value;
if (value === 'clear') {
currentValue = '';
prevValue = '';
operation = null;
updateDisplay();
} else if (value === '=') {
calculate();
} else if (value === 'sqrt') {
currentValue = Math.sqrt(parseFloat(currentValue));
updateDisplay();
} else if (value === '%') {
currentValue = parseFloat(currentValue) / 100;
updateDisplay();
} else if (isOperator(value)) {
handleOperator(value);
} else {
handleDigit(value);
}
});
});
function isOperator(value) {
return ['+', '-', '*', '/', '**'].includes(value);
}
function handleDigit(digit) {
if (currentValue.length < maxDigits) {
currentValue += digit;
updateDisplay();
}
}
function handleOperator(op) {
if (prevValue !== '') {
calculate();
}
operation = op;
prevValue = currentValue;
currentValue = '';
}
function calculate() {
if (prevValue === '' || operation === null) {
return;
}
let result;
const prev = parseFloat(prevValue);
const current = parseFloat(currentValue);
switch (operation) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
if (current === 0) {
showError('Cannot divide by zero');
return;
}
result = prev / current;
break;
case '**':
result = prev ** current;
break;
default:
return;
}
if (result.toString().length > maxDigits) {
showError('Result too large');
return;
}
currentValue = result.toString();
operation = null;
prevValue = '';
updateDisplay();
}
function updateDisplay() {
display.value = currentValue;
}
function showError(message) {
display.value = message;
setTimeout(() => {
currentValue = '';
prevValue = '';
operation = null;
updateDisplay();
}, 2000);
}