# Forming the nearest time using current time in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in a string, time, that represents time in the "HH:MM" form.

Our function is supposed to form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

For example, if the input to the function is

Input

const time = '19:34';

Output

const output = '19:39';

Output Explanation

The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.

## Example

Following is the code −

Live Demo

const time = '19:34';
const findClosestTime = (time = '') => {
const [a, b, c, d] = [time, time, time, time].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));

## Output

19:39