Skip to content

Commit 1b8320a

Browse files
authored
Update Counting Minutes I
1 parent df4b97f commit 1b8320a

File tree

1 file changed

+28
-30
lines changed

1 file changed

+28
-30
lines changed

Counting Minutes I

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,36 +31,34 @@
3131
* 3) Else return false *
3232
* *
3333
***************************************************************************************/
34-
function CountingMinutesI(str) {
35-
var time1Obj = {}, time2Obj = {}, timeDiff;
36-
37-
time1Obj = setTimeObject(str, 0);
38-
time2Obj = setTimeObject(str, 1);
39-
40-
if (time1Obj.ampm == time2Obj.ampm && time1Obj.tot > time2Obj.tot) {
41-
timeDiff = (((12 - time1Obj.hours + 12) * 60) - (time1Obj.mins)) + ((time2Obj.hours * 60) + time2Obj.mins);
42-
}
43-
else if (time1Obj.ampm == time2Obj.ampm && time1Obj.tot < time2Obj.tot) {
44-
timeDiff = ((time2Obj.hours * 60) + time2Obj.mins) - ((time1Obj.hours * 60) + time1Obj.mins);
45-
}
46-
else if (time1Obj.ampm !== time2Obj.ampm && time1Obj.ampm === "am") {
47-
timeDiff = (((12 - time1Obj.hours) * 60) - time1Obj.mins) + ((time2Obj.hours * 60) + time2Obj.mins);
48-
}
49-
else {
50-
timeDiff = (((12 - time1Obj.hours) * 60) - time1Obj.mins) + ((time2Obj.hours * 60) + time2Obj.mins);
34+
function CountingMinutesI(str) {
35+
function timeToMinutes(time) {
36+
let [hours, minutesPart] = time.split(':');
37+
let minutes = parseInt(minutesPart.slice(0, -2));
38+
let period = minutesPart.slice(-2);
39+
hours = parseInt(hours);
40+
41+
if (period === 'pm' && hours !== 12) {
42+
hours += 12;
43+
} else if (period === 'am' && hours === 12) {
44+
hours = 0;
5145
}
5246

53-
return timeDiff;
54-
}
55-
56-
function setTimeObject(str, num) {
57-
var arr = str.split("-");
58-
var tObject = {};
59-
60-
tObject.hours = Number(arr[num].slice(0,arr[num].length-2).split(":")[0]);
61-
tObject.mins = Number(arr[num].slice(0,arr[num].length-2).split(":")[1]);
62-
tObject.ampm = arr[num].slice(-2);
63-
tObject.tot = tObject.hours * 100 + tObject.mins;
64-
65-
return tObject;
47+
return hours * 60 + minutes;
48+
}
49+
50+
const [start, end] = str.split('-');
51+
const startMinutes = timeToMinutes(start);
52+
const endMinutes = timeToMinutes(end);
53+
54+
let difference = endMinutes - startMinutes;
55+
if (difference < 0) {
56+
difference += 1440; // add 24 hours worth of minutes
57+
}
58+
59+
return difference;
6660
}
61+
62+
// Test cases
63+
console.log(CountingMinutesI("9:00am-10:00am")); // Expected output: 60
64+
console.log(CountingMinutesI("1:00pm-11:00am")); // Expected output: 1320

0 commit comments

Comments
 (0)