diff --git a/index.html b/index.html index d422693..de681da 100644 --- a/index.html +++ b/index.html @@ -1,31 +1,34 @@ - - - - - - 타입스크립트로 계산기 만들기 - - -
-

혜인이의 계산기

-
-
-
- - - -

=

-

정답

-
- -
- - - + + + + + + + 타입스크립트로 계산기 만들기 + + + +
+

수빈이의 계산기

+
+
+
+ + + +

=

+

정답

+
+ +
+ + + + \ No newline at end of file diff --git a/src/htmlElements.ts b/src/htmlElements.ts new file mode 100644 index 0000000..1259d2b --- /dev/null +++ b/src/htmlElements.ts @@ -0,0 +1,15 @@ +export const input1: HTMLInputElement = document.querySelector( + "body > main > section > input[type=number]:nth-child(1)" +) as HTMLInputElement; +export const input2: HTMLInputElement = document.querySelector( + "body > main > section > input[type=number]:nth-child(3)" +) as HTMLInputElement; +export const operation: HTMLSelectElement = document.querySelector( + "body > main > section > select" +) as HTMLSelectElement; +export const calculateButton: HTMLButtonElement = document.querySelector( + "body > main > button" +) as HTMLButtonElement; +export const answer: HTMLHeadingElement = document.querySelector( + "body > main > section > h3" +) as HTMLHeadingElement; diff --git a/src/main.ts b/src/main.ts index e69de29..6ea6e01 100644 --- a/src/main.ts +++ b/src/main.ts @@ -0,0 +1,49 @@ +import { + answer, + calculateButton, + input1, + input2, + operation, +} from "./htmlElements"; + +calculateButton.addEventListener("click", () => { + if (!checkInput()) return; // 입력 필드 검증 + + const num1: number = Number(input1.value); // 입력값을 숫자로 변경 + const num2: number = Number(input2.value); + + const result = calculate(num1, num2, operation.value); // 결과 연산 + + answer.textContent = String(result); // 정답 출력 +}); + +/* 입력 필드 검증 함수 */ +function checkInput() { + const isInputEmpty: boolean = isEmpty(input1.value, input2.value); + if (isInputEmpty) { + alert("뭐 잊은거 없어?"); + return false; + } + return true; +} + +/* 입력 필드가 비었는지 확인하는 함수 */ +function isEmpty(num1: string, num2: string): boolean { + return num1 === "" || num2 === ""; +} + +/* 결과 연산 함수 */ +function calculate(num1: number, num2: number, sign: string): number { + switch (sign) { + case "sum": + return num1 + num2; + case "sub": + return num1 - num2; + case "mul": + return num1 * num2; + case "divide": + return num1 / num2; + default: + return 0; + } +} diff --git a/tsconfig.json b/tsconfig.json index 75abdef..ea003a6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,7 +10,7 @@ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, - "isolatedModules": true, + "isolatedModules": false, "noEmit": true, /* Linting */