
💩 리팩터링 전
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const merry = document.querySelector(".js-clock"); | |
function getClock() { | |
const christmas = new Date("2021, 12, 25"); | |
const date = new Date(); | |
const timeGap = christmas - date; | |
const xDay = Math.floor(timeGap / (1000 * 60 * 60 * 24)); | |
const xHours = Math.floor( | |
(timeGap - xDay * 1000 * 60 * 60 * 24) / (1000 * 60 * 60) | |
); | |
const xMinutes = Math.floor((timeGap % (60 * 60 * 1000)) / (60 * 1000)); | |
const xSeconds = Math.floor((timeGap % (60 * 1000)) / 1000); | |
const day = String(xDay).padStart(2, "0"); | |
const hours = String(xHours).padStart(2, "0"); | |
const minutes = String(xMinutes).padStart(2, "0"); | |
const seconds = String(xSeconds).padStart(2, "0"); | |
merry.innerText = `${day}d ${hours}h ${minutes}m ${seconds}s`; | |
} | |
getClock(); | |
setInterval(getClock, 1000); |
🥰 리팩터링 후
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MERRY = document.querySelector(".js-clock"); | |
const CHRISTMAS = new Date("2021, 12, 25"); | |
const SECOND = 1000; | |
const MINUTE = 60 * SECOND; | |
const HOUR = 60 * MINUTE; | |
const DAY = 24 * HOUR; | |
function getClock() { | |
const date = new Date(); | |
const timeGap = CHRISTMAS - date; | |
const gap = remainTime(timeGap); | |
MERRY.innerText = `${gap.day}d ${gap.hours}h ${gap.minutes}m ${gap.seconds}s`; | |
} | |
function remainTime(timeGap) { | |
const xDay = Math.floor(timeGap / DAY); | |
const xHours = Math.floor((timeGap % DAY) / HOUR); | |
const xMinutes = Math.floor((timeGap % (HOUR)) / (MINUTE)); | |
const xSeconds = Math.floor((timeGap % (MINUTE)) / SECOND); | |
const day = String(xDay).padStart(2, "0"); | |
const hours = String(xHours).padStart(2, "0"); | |
const minutes = String(xMinutes).padStart(2, "0"); | |
const seconds = String(xSeconds).padStart(2, "0"); | |
return {day, hours, minutes, seconds}; | |
} | |
function init() { | |
getClock(); | |
setInterval(getClock, 1000); | |
} | |
init(); |
🤔 느낀 점
- 자바스크립트에서 시간관련 함수가 있나 검색하는 시간이 꽤 길었습니다.
=> 결론은 시간 관련 함수 없이 예시로 나온 로직으로 리팩터링 하는 것이였습니다.
=> 생각해보니 로직을 변경하면 리팩터링이라고 하기 좀 뭐한 것 같습니다. - 어떻게 해야할지 고민하다가 잘 작성하신분 코드를 참고했습니다.
=> 갓갓갓 플린님 링크
=> 타입스크립트로 리팩터링 하신 분
=> 개인적으로 되게 깔끔하다고 느낀 코드 - 확실히 어떤 코드가 깨끗한 코드이고 더려운 코드인지 판단 할 수 있게 된것 같습니다.
반응형