Skip to content

Commit 9a76928

Browse files
committed
Refactor - Added formatTimeDisplay utility function to reduce code duplication
1 parent 50a0653 commit 9a76928

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

Sprint-3/alarmclock/alarmclock.js

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,23 @@ const MILLISECONDS_PER_SECOND = 1000;
44

55
let intervalId;
66

7+
/**
8+
* Formats time in seconds to MM:SS format
9+
* @param {number} totalSeconds - The time in seconds to format
10+
* @returns {string} Formatted time string in "Time Remaining: MM:SS" format
11+
*/
12+
function formatTimeDisplay(totalSeconds) {
13+
const minutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE);
14+
const seconds = totalSeconds % SECONDS_PER_MINUTE;
15+
16+
return (
17+
"Time Remaining: " +
18+
String(minutes).padStart(2, "0") +
19+
":" +
20+
String(seconds).padStart(2, "0")
21+
);
22+
}
23+
724
function setAlarm() {
825
const input = document.getElementById("alarmSet");
926
const heading = document.getElementById("timeRemaining");
@@ -18,29 +35,22 @@ function setAlarm() {
1835

1936
clearInterval(intervalId);
2037

21-
heading.innerText =
22-
"Time Remaining: " +
23-
String(Math.floor(totalSeconds / SECONDS_PER_MINUTE)).padStart(2, "0") +
24-
":" +
25-
String(totalSeconds % SECONDS_PER_MINUTE).padStart(2, "0");
38+
heading.innerText = formatTimeDisplay(totalSeconds);
2639

2740
intervalId = setInterval(() => {
2841
totalSeconds--;
2942

3043
if (totalSeconds <= 0) {
31-
heading.innerText = "Time Remaining: 00:00";
44+
heading.innerText = formatTimeDisplay(0);
3245
clearInterval(intervalId);
3346
playAlarm();
3447
return;
3548
}
3649

37-
heading.innerText =
38-
"Time Remaining: " +
39-
String(Math.floor(totalSeconds / SECONDS_PER_MINUTE)).padStart(2, "0") +
40-
":" +
41-
String(totalSeconds % SECONDS_PER_MINUTE).padStart(2, "0");
50+
heading.innerText = formatTimeDisplay(totalSeconds);
4251
}, MILLISECONDS_PER_SECOND);
4352
}
53+
4454
// DO NOT EDIT BELOW HERE
4555

4656
var audio = new Audio("alarmsound.mp3");

0 commit comments

Comments
 (0)