-
-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathformat-time.js
More file actions
85 lines (73 loc) · 2.26 KB
/
format-time.js
File metadata and controls
85 lines (73 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// This is the latest solution to the problem from the prep.
// Make sure to do the prep before you do the coursework
// Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find.
/*
edge cases to be checked:
1. 00:00
2. 24:00
3. 12:00
4. 12:01
5. 00:01
*/
function pad(num) {
return num.toString().padStart(2, "0");
}
function formatAs12HourClock(time) {
const hours = Number(time.slice(0, 2));
const minutes = Number(time.slice(3, 5));
if (hours == 0 || hours == 24) {
return `12:${pad(minutes)} am`;
} else if (hours > 12) {
return `${pad(hours - 12)}:00 pm`;
} else if (hours == 12) {
return `${time} pm`;
} else return `${time} am`;
}
let currentOutput = formatAs12HourClock("08:00");
let targetOutput = "08:00 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("23:00");
targetOutput = "11:00 pm";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("13:00");
targetOutput = "01:00 pm";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("00:00");
targetOutput = "12:00 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("24:00");
targetOutput = "12:00 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("12:00");
targetOutput = "12:00 pm";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("12:01");
targetOutput = "12:01 pm";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
currentOutput = formatAs12HourClock("00:01");
targetOutput = "12:01 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);