문제
"HH:MM" 형식으로 시간을 나타내는 문자열, 시간을 받는 JavaScript 함수를 작성해야 합니다.
우리의 함수는 현재 숫자를 재사용하여 다음으로 가장 가까운 시간을 형성해야 합니다. 숫자를 재사용할 수 있는 횟수에는 제한이 없습니다.
예를 들어 함수에 대한 입력이
인 경우입력
const time = '19:34';
출력
const output = '19:39';
출력 설명
숫자 1, 9, 3, 4에서 다음으로 가장 가까운 시간은 5분 후에 발생하는 19:39입니다. 23시간 59분 후에 발생하기 때문에 19:33이 아닙니다.
예시
다음은 코드입니다 -
const time = '19:34';
const findClosestTime = (time = '') => {
const [a, b, c, d] = [time[0], time[1], time[3], time[4]].map(x =>Number(x));
const sorted = [a, b, c, d].sort((x, y) => x - y)
const d2 = sorted.find(x => x > d)
if (d2 > d) {
return `${a}${b}:${c}${d2}`
}
const c2 = sorted.find(x => x > c && x <= 5)
const min = Math.min(a, b, c, d)
if (c2 > c) {
return `${a}${b}:${c2}${min}`
}
const b2 = sorted.find(x => x > b && a * 10 + x <= 24)
if (b2 > b) {
return `${a}${b2}:${min}${min}`
}
const a2 = sorted.find(x => x > a && x <= 2)
if (a2 > a) {
return `${a2}${min}:${min}${min}`
}
return `${min}${min}:${min}${min}`
};
console.log(findClosestTime(time)); 출력
19:39