[TIL] Day9 #Coding:계산기 기능

Beanxx·2022년 5월 6일
0

TIL

목록 보기
9/120
post-thumbnail

[TIL] Day9
[SEB FE] Day9

✔️ 계산기 기능 구현

  • Bare Minimum Requirements: 소프트웨어가 그 역할을 하기에 필요한 최소한의 요구사항
// Bare Minimum Requirements
const calculator = document.querySelector(".calculator");
const buttons = calculator.querySelector(".calculator__buttons");

const firstOperend = document.querySelector(".calculator__operend--left");
const operator = document.querySelector(".calculator__operator");
const secondOperend = document.querySelector(".calculator__operend--right");
const calculatedResult = document.querySelector(".calculator__result");

function calculate(n1, operator, n2) {
  let result = 0;
  
  n1 = parseFloat(n1);
  n2 = parseFloat(n2);

  if (operator === "+") {
    result = n1 + n2;
  } else if (operator === "-") {
    result = n1 - n2;
  } else if (operator === "*") {
    result = n1 * n2;
  } else if (operator === "/") {
    result = n1 / n2;
  }
  return String(result);
}

// 버튼을 눌렀을 때 작동하는 함수
buttons.addEventListener("click", function (event) {
  const target = event.target; // 클릭된 HTML 엘리먼트의 정보 저장
  const action = target.classList[0]; // 클릭된 HTML 엘리먼트에 클래스 정보를 가져옴
  const buttonContent = target.textContent; // 클릭된 HTML 엘리먼트의 텍스트 정보를 가져옴

  // 클릭된 HTML 엘리먼트가 button이면
  if (target.matches("button")) {
    // 버튼의 클래스가 number이면
    if (action === "number") {
      if (firstOperend.textContent === "0") { // 0은 초기값
        firstOperend.textContent = buttonContent;
      } else {
        secondOperend.textContent = buttonContent;
      }
    }

    if (action === "operator") {
      operator.textContent = buttonContent;
    }

    if (action === "decimal") {
      console.log("소수점 버튼");
    }

    if (action === "clear") {
      console.log("초기화 버튼");
      firstOperend.textContent = "0";
      operator.textContent = "+";
      secondOperend.textContent = "0";
      calculatedResult.textContent = "0";
    }

    if (action === "calculate") {
      console.log("계산 버튼!!");
      calculatedResult.textContent = calculate(
        firstOperend.textContent,
        operator.textContent,
        secondOperend.textContent
      );
    }
  }
});

  • User Flow: 사용자가 서비스나 프로그램을 어떻게 사용할지 가정하는 것
// + Advanced Challenge test & Nightmare test
const display = document.querySelector(".calculator__display--for-advanced");
let firstNum, operatorForAdvanced, previousKey, previousNum;

// 버튼을 눌렀을 때 작동하는 함수
buttons.addEventListener("click", function (event) {
  const target = event.target;
  const action = target.classList[0];
  const buttonContent = target.textContent;

  if (target.matches("button")) {
    
    if (action === "number") {
      if (display.textContent === "0" || previousKey === "operator") { // 화면 출력값이 초기값 0 이거나 연산자를 입력한 경우
        display.textContent = buttonContent;
      } else {
        display.textContent += buttonContent;
      }
      previousKey = "number";
    }
    
    if (action === "operator") {
      // 보이지 않지만, 저장이 되어 있어야 함 -> 변수에 할당
      operatorForAdvanced = buttonContent;
      // 현재 화면에 있는 숫자 저장 -> 변수에 할당
      firstNum = display.textContent;
      // 방금 뭐 눌렀는지도 저장
      previousKey = "operator";
    }
    
    if (action === "decimal") {
    }
    
    if (action === "clear") {
      console.log("초기화 버튼");
      // 1. 계산기에 입력되었던 첫 번째 값
      firstNum = undefined;
      // 2. 연산자
      operatorForAdvanced = undefined;
      // 3. 계산기에 입력되었던 두 번째 값
      previousNum = undefined;
      // 4. 화면
      display.textContent = "0";
      
      previousKey = "clear";
    }
    
    
    if (action === "calculate") {
      previousNum = display.textContent;

      // 계산기의 화면에 calculate 함수 결과 출력
      display.textContent = calculate(
        firstNum,
        operatorForAdvanced,
        previousNum
      );
      previousKey = "calculate";
    }
  }
});
➰ Test Case 12개 미통과 👉🏻
a. 연산자 '-', '/'를 눌렀을 때 enter를 여러번 누를 경우의 test case
b. 소수점 연산 test case
✅ 내일 복습하고 마저 통과하기
  • document.querySelector(selectors) : 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환 (일치하는 요소가 없으면 null 반환)

  • textContent 속성: 입력된 내용을 간단하게 변경할 수 있음 (모든 텍스트를 그대로 가져옴)
    ✋ = innerText 속성 (불필요한 공백을 제거하고 텍스트로 반환)
    ✋ html 엘리먼트 안에 있는 값은 ‘문자열’


    📎 parseIntparseFloat의 차이

    • parseInt(): 문자열을 정수로 바꾸는 함수

    • parseFloat(): 문자열을 실수로 바꾸는 함수


    📎 변수 선언 2가지 방법

    1. let: 재할당 가능
    2. const: 재할당 불가능
profile
FE developer

0개의 댓글