Created
September 21, 2018 15:34
-
-
Save satya-jugran/b8ea6e18efef763be8e8b11d0b490db6 to your computer and use it in GitHub Desktop.
Find most free time of the day. Input string will represent full day filled with events that span from time X to time Y. Test case : 1) Input - "12:15PM-02:00PM","09:00AM-10:00AM","10:30AM-12:00PM" | Output - 00:30 2) Input - "12:15PM-02:00PM","09:00AM-12:11PM","02:02PM-04:00PM" | Output - 00:04
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function MostFreeTime(str) { | |
var dates = []; | |
str.split(",").forEach(d => { | |
dt = d.substring(1, d.length - 1).split("-"); | |
s = dt[0]; | |
dt[0] = s.substr(s.length - 2, 2) == "AM" ? s.substr(0, 5) : | |
(Number.parseInt(s.substr(0, 2)) < 12 ? Number.parseInt(s.substr(0, 2)) + 12 + ":" + s.substr(3, 2) : s.substr(0, 5)); | |
s = dt[1]; | |
dt[1] = s.substr(s.length - 2, 2) == "AM" ? s.substr(0, 5) : | |
(Number.parseInt(s.substr(0, 2)) < 12 ? Number.parseInt(s.substr(0, 2)) + 12 + ":" + s.substr(3, 2) : s.substr(0, 5)); | |
dates.push({ | |
from: Date.parse("2018-01-01T" + dt[0] + ":00.000Z"), | |
to: Date.parse("2018-01-01T" + dt[1] + ":00.000Z") | |
}) | |
}); | |
dates.sort(function (dt1, dt2) { | |
return dt2.from < dt1.from | |
}) | |
max = Number.MIN_VALUE; | |
for (var i = dates.length - 1; i > 0; i--) { | |
diff = dates[i].from - dates[i - 1].to; | |
if (diff > max) max = diff; | |
} | |
d = new Date(max); | |
return d.toISOString().substr(11, 5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MostFreeTime('"12:15PM-02:00PM","09:00AM-10:00AM","10:30AM-12:00PM"')
MostFreeTime('"12:15PM-02:00PM","09:00AM-12:11PM","02:02PM-04:00PM"')