DAY 11

🔖 오늘 읽은 범위 : 미션! 더러운 코드를 고쳐라!


Before

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);

After

var merry = document.querySelector(".js-clock");

function getClock() {
    const now = new Date();
    const christmas = getDateWithThisYear(12, 25);
    const diff = getDiff(now, christmas);
    const date = MillisecondDate.convertToDate(diff);
    return formatting(date.day, date.hour, date.minute, date.second);
}

function getDateWithThisYear(month, day) {
    const thisYear = new Date().getFullYear(); 
    return new Date(thisYear, month, day);
}

function getDiff(now, d_day) {
    return d_day - now;
}

function formatting(day, hour, minute, second) {
    const dayText = pad(day)
    const hourText = pad(hour)
    const minuteText = pad(minute)
    const secondText = pad(second)
    return `${dayText}d ${hourText}h ${minuteText}m ${secondText}s`;
}

function pad(target) {
    return String(target).padStart(2, "0");
}

class MillisecondDate {
    constructor(millisecond, second, minute, hour, day) {
        this.millisecond = millisecond;
        this.second = second;
        this.minute = minute;
        this.hour = hour;
        this.day = day;
    }

    static convertToDate(time) {
        let milliseconds, seconds, minutes, hours, days;
        
        milliseconds = time % 1000;
        time = (time - milliseconds) / 1000;

        seconds = time % 60;
        time = (time - seconds) / 60;

        minutes = time % 60;
        time = (time - minutes) / 60;

        hours = time % 24;
        time = (time - hours) / 24;

        days = time;

        return new this(milliseconds, seconds, minutes, hours, days);
    }
}

setInterval(function () {
    merry.innerText = getClock();
}, 1000);

<aside> 🤔 오늘 읽은 소감은? 떠오르는 생각을 가볍게 적어보세요

</aside>

코드를 수정하는데 꽤 많은 시간이 소요되었다. 1시간 반 정도?! 계속하다보면 실력이 늘고 시간이 줄어들 것이라고 기대한다. 다른 사람들의 수정 내용도 궁금하다.

클린코드 내용을 요약한 cheetsheet 같은걸 만들어서 보면서 수정하면 좋을 것 같다.

<aside> 🔎 궁금한 내용이 있거나, 잘 이해되지 않는 내용이 있다면 적어보세요.

</aside>

기록하신 TIL을 공유해주세요 - TIL 출석표

클린코드_스케쥴러_TIL 출석표 (노개북1기)

소감 3줄 요약

https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=dolhim.notion.site/TIL-2022-02-01-DAY-11-07ad6dcc988143fa81e9df5df6944834