scale(seconds, 0, 60, 0, 360)이 뭐지!?

김민성·2023년 7월 15일

https://github.com/bradtraversy/50projects50days/blob/master/theme-clock/script.js

trouble

깃허브에 있는 50projects50days의 시계어플 코드를 공부하던 중 scale(seconds, 0, 60, 0, 360)이라는 함수가 나왔다.

function setTime() {
    const time = new Date();
    const month = time.getMonth()
    const day = time.getDay()
    const date = time.getDate()
    const hours = time.getHours()
    const hoursForClock = hours >= 13 ? hours % 12 : hours;
    const minutes = time.getMinutes()
    const seconds = time.getSeconds()
    const ampm = hours >= 12 ? 'PM' : 'AM'

    hourEl.style.transform = `translate(-50%, -100%) rotate(${scale(hoursForClock, 0, 12, 0, 360)}deg)`
    minuteEl.style.transform = `translate(-50%, -100%) rotate(${scale(minutes, 0, 60, 0, 360)}deg)`
    secondEl.style.transform = `translate(-50%, -100%) rotate(${scale(seconds, 0, 60, 0, 360)}deg)`

    timeEl.innerHTML = `${hoursForClock}:${minutes < 10 ? `0${minutes}` : minutes} ${ampm}`
    dateEl.innerHTML = `${days[day]}, ${months[month]} <span class="circle">${date}</span>`
}

1st try - 공식문서

CSS에서 scale()는 자주 사용했어서 그걸 활용한 진화버전이라고 생각하고 공식문서를 찾아보았는데 5개의 인수가 활용된 것은 없었다.

2nd try - 구글링

구글링해보았으나 작성된 코드만 나와있고 그것을 분석한 글은 없었다. 어려운 코드였다면 설명하거나 분석한 글이 있었을텐데 없었다. 이때 다시 코드를 확인했었어야했다...

3rd try - 동료

같이 공부하는 코딩동료들에게 DM을 보내 어떤 코드인 줄 아느냐고 여쭤보았다. 답을 기다리는 동안 다시 코드를 읽어봤는데...

shooting

사용되는 컨텍스트 바깥에 전역 컨텍스트로 scale이 정의되어있었다. 사용자 정의함수였던 것이었다.

function setTime() {
    const time = new Date();
    const month = time.getMonth()
    const day = time.getDay()
    const date = time.getDate()
    const hours = time.getHours()
    const hoursForClock = hours >= 13 ? hours % 12 : hours;
    const minutes = time.getMinutes()
    const seconds = time.getSeconds()
    const ampm = hours >= 12 ? 'PM' : 'AM'

    hourEl.style.transform = `translate(-50%, -100%) rotate(${scale(hoursForClock, 0, 12, 0, 360)}deg)`
    minuteEl.style.transform = `translate(-50%, -100%) rotate(${scale(minutes, 0, 60, 0, 360)}deg)`
    secondEl.style.transform = `translate(-50%, -100%) rotate(${scale(seconds, 0, 60, 0, 360)}deg)`

    timeEl.innerHTML = `${hoursForClock}:${minutes < 10 ? `0${minutes}` : minutes} ${ampm}`
    dateEl.innerHTML = `${days[day]}, ${months[month]} <span class="circle">${date}</span>`
}

// StackOverflow https://stackoverflow.com/questions/10756313/javascript-jquery-map-a-range-of-numbers-to-another-range-of-numbers
const scale = (num, in_min, in_max, out_min, out_max) => {
    return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

동료에게 모르겠다고 물었던 나 자신이 너무 창피했다. 그리고 너무 미안했다.

느낀점

  1. 모르는 코드가 나온다면 일단 검색하여 관련 코드를 읽자.
    -> 이것만 했어도 문제가 해결되었다...(멍청이...)

  2. 함수명을 상세히 작성하자. 그리고 일반적으로 사용되는 함수명과 겹치게 작성하지 말자.

  3. 실행컨텍스트를 잘 활용하자. 컨텍스트 안에서만 활용되는 함수는 전역으로 빼지말자.

  4. 무작정 묻지 말자 제발... 민폐다

profile
'WHY'를 묻고 reason을 공부하는 개발외ㅓ인

0개의 댓글