在 JavaScript 中使用当前时间形成最近的时间
问题
我们需要编写一个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
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话