diff --git a/README.md b/README.md index 13420b29f..e10076a01 100644 --- a/README.md +++ b/README.md @@ -1 +1,25 @@ -# javascript-calculator-precourse \ No newline at end of file +# javascript-calculator-precourse + +# 정상 동작 + +1. 사용자의 입력값을 받는다. +2. 구분자의 통일을 위해 ":" 구분자를 "," 구분자로 변경한다. +3. 커스텀 구분자가 존재하는지 확인한다. +4. 커스텀 구분자가 존재한다면 커스텀 구분자가 무엇인지 추출한다. +5. 커스텀 구분자가 "-" 일 경우 음수가 포함되었는지, 음수가 포험되어있다면 에러 처리를 하기 위해 확인한다. "-"를 연속으로 입력하면 "-"구분자에 음수를 더한것으로 간주한다. +6. 추출한 커스텀 구분자를 "," 구분자로 전부 변경한다. +7. 커스텀 구분자를 지정하는 "//"와 "\n" 기호를 없앤다. +8. 완성된 문자열이 적합한 문자열인지 확인한다. +9. 완성된 문자열을 ","구분자를 기준으로 나누어 문자열의 배열로 만든다. +10. 문자열의 배열길이만큼 for문을 돌며 각 요소에 접근한다. +11. 각 요소를 숫자로 변환한다. +12. 변환된 각 요소가 0 이상의 숫자가 맞는지 확인한다. +13. 적합한 숫자라면 총 결과 값에 그 숫자를 더한다. +14. 결과를 출력한다. + +# 예외 처리 + +1. 커스텀 문자가 올바르게 작성되지 않은 경우 +2. 구분자나 커스텀 구분자가 아닌 다른 문자가 입력되는 경우 +3. 입력된 숫자가 음수인 경우 + 위의 세가지 경우에 에러를 발생시키고 어플리케이션이 종료되도록 합니다. diff --git a/src/App.js b/src/App.js index 091aa0a5d..c26c0841d 100644 --- a/src/App.js +++ b/src/App.js @@ -1,5 +1,73 @@ +import { Console } from "@woowacourse/mission-utils"; + class App { - async run() {} + async run() { + const input = await Console.readLineAsync("입력하세요.\n"); + + const replacedString = input.replaceAll(":", ","); + let resultString = replacedString; + + if (validateIncludeCustomSeperator(replacedString)) { + const customSeprator = getCustomSeperator(resultString); + + if (customSeprator === "-") { + validateMinusNumberInDashSperator(resultString); + } + + resultString = resultString.replaceAll(customSeprator, ","); + resultString = resultString.replaceAll("//,\\n", ""); + } + + validateAcceptableString(resultString); + + const stringArr = resultString.split(","); + let resultNumber = 0; + for (let i = 0; i < stringArr.length; i++) { + const number = Number(stringArr[i]); + validateMinusNumber(number); + + resultNumber += number; + } + + Console.print(`결과 : ${resultNumber}`); + } } +const validateIncludeCustomSeperator = (string) => { + const CUSTOM_SPERATOR_REGEX = /\/\/.+\\n/; + return CUSTOM_SPERATOR_REGEX.test(string); +}; + +const getCustomSeperator = (string) => { + const MATCH_REGEX = /\/\/(.*?)\\n/; + const match = string.match(MATCH_REGEX); + + if (match) { + return match[1]; + } else { + throw new Error("[ERROR] 올바르지 않은 형식입니다."); + } +}; + +const validateMinusNumberInDashSperator = (string) => { + if (string.indexOf("--") >= 0) { + throw new Error("[ERROR] 음수는 입력 불가능합니다."); + } +}; + +const validateAcceptableString = (string) => { + const ACCEPTABLE_REGEX = /^[0-9,]+$/; + + if (!ACCEPTABLE_REGEX.test(string)) { + throw new Error("[ERROR] 올바르지 않은 문자를 포함하고 있습니다."); + } +}; + +const validateMinusNumber = (number) => { + if (number < 0) { + throw new Error("[ERROR] 음수는 입력 불가능합니다."); + } +}; + + export default App;