이번에는 사칙연산이 가능한 간단한 계산기를 만들어볼건데, 쿵쿵따 만들듯이 먼저 순서도를 그려보고 시작 할 것이다.
자, 일단 내가 정리한 순서도는 이렇다.
숫자 연산자 숫자 = 계산 후 계산의 결과 종료❗
그러려면 가장 필요 한 건
<div id="calculator">
<div id="display">0</div>
<button>7</button>
<button>8</button>
<button>9</button>
<button>+</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>-</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>x</button>
<button>0</button>
<button>c</button>
<button>=</button>
<button>/</button>
</div>
필요한 걸 다 만들어 주었다. c는 초기화를 시켜주는 버튼으로 하나 더 만들어봤다. 그럼 이렇게 간단한 계산기 모양이 만들어진다.
+ 이벤트 리스너가 추가되어야 할 것
✅ 숫자버튼 : 누르면 화면에 표시 되어야 한다.
✅ 연산자 버튼 : 누르면 화면에 표시되고 연산자를 설정한다.
✅ = 버튼 : 숫자와 연산자에 따라 계산이 되어야 한다.
✅ c 버튼 : 모든 변수를 초기화 시켜야 한다.
그리고 계산기의 기능에서 내가 추가 하고 싶은 기능
✅ 연산자 연속 클릭 방지 로직 개선.
✅ 0으로 나누기 처리.
✅ 숫자 입력 길이 제한.
<script>
const display = document.querySelector("#display");
let currentInput = "";
let previousInput = "";
let operator = null;
function onButtonClick(value) {
if (!isNaN(value)) {
handleNumber(value);
} else if (["+", "-", "x", "/"].includes(value)) {
handleOperator(value);
} else if (value === "=") {
calculate();
} else if (value.toLowerCase() === "c") {
clearCalculator();
}
}
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", (e) => {
const value = e.target.textContent;
onButtonClick(value);
});
});
function updateDisplay(value) {
display.textContent = value;
}
function handleNumber(num) {
if (currentInput.length >= 10) return;
currentInput += num;
updateDisplay(currentInput);
}
function handleOperator(op) {
if (currentInput === "" && operator) {
return;
}
if (currentInput === "") return;
if (previousInput && currentInput && operator) {
calculate();
}
previousInput = currentInput;
currentInput = "";
operator = op;
}
</script>
💡
살펴보자면 일단 모든 버튼을 클릭 했을 때 클릭한 버튼의 value가 화면에 나와야 한다. 그러기위해서 일단은 함수를 하나 만들어 주었다.
onButtonClick()
은 매개 변수로 클릭한 value를 받고,handleNumber(value);
를 호출해서 입력값 업데이트handleOperator(value);
를 호출해서 연산 준비💚숫자 처리 함수 handleNumber()
function handleNumber(num) {
if (currentInput.length >= 10) return;
currentInput += num;
updateDisplay(currentInput);
}
💚 연산자 함수 handleOperator()
function handleOperator(op) {
if (currentInput === "" && operator) {
return;
}
if (currentInput === "") return;
if (previousInput && currentInput && operator) {
calculate();
}
previousInput = currentInput;
currentInput = "";
operator = op;
}
💚 계산 함수 Calculate()
function calculate() {
if (!previousInput || !currentInput || !operator) {
return;
}
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
const operations = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
x: (a, b) => a * b,
"/": (a, b) => (b === 0 ? "Error" : a / b),
};
const result = operations[operator]?.(prev, current) ?? "Error";
currentInput = result;
operator = null;
previousInput = "";
updateDisplay(currentInput);
}
💚 초기화 함수 clearCalculator()
function clearCalculator() {
currentInput = "";
previousInput = "";
operator = null;
updateDisplay("0");
}
완성된 결과물