समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो एक स्ट्रिंग, time, लेता है जो "HH:MM" रूप में समय को दर्शाता है।
हमारा फ़ंक्शन वर्तमान अंकों का पुन: उपयोग करके अगला निकटतम समय बनाने वाला है। एक अंक को कितनी बार भी पुन: उपयोग किया जा सकता है, इसकी कोई सीमा नहीं है।
उदाहरण के लिए, यदि फ़ंक्शन का इनपुट है
इनपुट
const time = '19:34';
आउटपुट
const output = '19:39';
आउटपुट व्याख्या
अंकों 1, 9, 3, 4 को चुनकर अगला निकटतम समय 19:39 है, जो 5 मिनट बाद होता है। यह 19:33 नहीं है, क्योंकि यह 23 घंटे और 59 मिनट बाद होता है।
उदाहरण
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