CodeWars: Human readable duration format Solution
Readability rather than trying to be cleverApproach
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"34 const addPlural = (number, noun) =>5 number === 0 ? "" : `${number} ${noun}${number === 1 ? "" : "s"}`67 const SECOND = 18 const MINUTE = SECOND * 609 const HOUR = MINUTE * 6010 const DAY = HOUR * 2411 const YEAR = DAY * 3651213 const years = Math.floor(seconds / YEAR)14 seconds %= YEAR15 const days = Math.floor(seconds / DAY)16 seconds %= DAY17 const hours = Math.floor(seconds / HOUR)18 seconds %= HOUR19 const minutes = Math.floor(seconds / MINUTE)20 seconds %= MINUTE2122 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
Comments
Loading comments...
Tags
codewars
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Previous Post
LeetCode: Sum of Digits of String After Convert
Solving a problem in one go is such a good feeling