CodeWars: Human readable duration format Solution

Readability rather than trying to be clever

Approach

Convert to years, days, hours, minutes, and seconds

Join by , and use regex to replace the last occurence

Implementation

1function formatDuration(seconds) {
2 if (seconds === 0) return "now"
3
4 const addPlural = (number, noun) =>
5 number === 0 ? "" : `${number} ${noun}${number === 1 ? "" : "s"}`
6
7 const SECOND = 1
8 const MINUTE = SECOND * 60
9 const HOUR = MINUTE * 60
10 const DAY = HOUR * 24
11 const YEAR = DAY * 365
12
13 const years = Math.floor(seconds / YEAR)
14 seconds %= YEAR
15 const days = Math.floor(seconds / DAY)
16 seconds %= DAY
17 const hours = Math.floor(seconds / HOUR)
18 seconds %= HOUR
19 const minutes = Math.floor(seconds / MINUTE)
20 seconds %= MINUTE
21
22 return [
23 [years, "year"],
24 [days, "day"],
25 [hours, "hour"],
26 [minutes, "minute"],
27 [seconds, "second"],
28 ]
29 .map(([number, noun]) => addPlural(number, noun))
30 .filter(Boolean)
31 .join(", ")
32 .replace(/,\s([^,]+)$/, " and $1")
33}

References

Original problem

Regex replace last occurence

Comments

Loading comments...

Tags

codewars

string

Next Post

Hackerrank: Grading Students

Previous Post

LeetCode: Sum of Digits of String After Convert

Solving a problem in one go is such a good feeling

HoningJS

Search Posts