CodeWars 코딩 문제 2021/04/15 - Human readable duration format

이호현·2021년 4월 15일
0

Algorithm

목록 보기
102/138

[문제]

Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.

The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.

It is much easier to understand with an example:

formatDuration(62) // returns "1 minute and 2 seconds"
formatDuration(3662) // returns "1 hour, 1 minute and 2 seconds"

For the purpose of this Kata, a year is 365 days and a day is 24 hours.

Note that spaces are important.

Detailed rules
The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.

Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.

A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.

A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.

(요약) 주어진 초를 계산해서 초, 분, 시간, 일, 년의 문자열로 변환해라.

[풀이]

function formatDuration (seconds) {
  if(!seconds) return 'now';

  let answer = '';
  const arr = ['second', 60, 'minute', 60, 'hour', 24, 'day', 365, 'year'];
  let index = 1;
  let count = 0;
  let check = false;

  while(seconds) {
    if(check) {
      answer = (count > 1 ? ', ' : ' and ') + answer;
    }

    if(seconds >= arr[index]) {
      const devidedNum = seconds % arr[index];

      if(devidedNum) {
        answer = `${devidedNum} ${arr[index - 1]}${devidedNum > 1 ? 's' : ''}` + answer;
        count++;
        check = true;
      }
      else {
        check = false;
      }

      seconds = (seconds / arr[index])|0;
      index += 2;
    }
    else {
      answer = `${seconds} ${arr[index - 1]}${seconds > 1 ? 's' : ''}` + answer;
      break;
    }
  }

  return answer;
}

우선 초가 0이면 nowreturn.

배열에 번갈아가며 시간 단위와 나눌 수를 넣고, 차례대로 계산해줌.

문제 자체는 쉬운편인데 return할 문자열 형식 맞추는게 힘들었음.

profile
평생 개발자로 살고싶습니다

0개의 댓글