-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.js
More file actions
42 lines (34 loc) · 1016 Bytes
/
Copy pathsolution.js
File metadata and controls
42 lines (34 loc) · 1016 Bytes
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
/**
* Human Readable Duration Format
* Codewars kata solution
*
* @param {number} seconds - Non-negative integer duration in seconds
* @returns {string} Human-readable duration
*/
function formatDuration(seconds) {
if (seconds === 0) return "now";
const units = [
["year", 365 * 24 * 60 * 60],
["day", 24 * 60 * 60],
["hour", 60 * 60],
["minute", 60],
["second", 1]
];
const result = [];
for (const [name, value] of units) {
const count = Math.floor(seconds / value);
if (count > 0) {
seconds %= value;
result.push(`${count} ${name}${count > 1 ? "s" : ""}`);
}
}
if (result.length === 1) return result[0];
return `${result.slice(0, -1).join(", ")} and ${result.at(-1)}`;
}
module.exports = formatDuration;
// Manual examples
if (require.main === module) {
console.log(formatDuration(0)); // now
console.log(formatDuration(62)); // 1 minute and 2 seconds
console.log(formatDuration(3662)); // 1 hour, 1 minute and 2 seconds
}