使用 JavaScript 求最近的時間


問題

我們需要編寫一個 JavaScript 函式,它接收一個字串時間,表示“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

更新於: 24-Apr-2021

392 次瀏覽

開始你的職業生涯

完成課程獲取認證

立即開始
廣告
© . All rights reserved.