# 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

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function 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 = 18  const MINUTE = SECOND * 609  const HOUR = MINUTE * 6010  const DAY = HOUR * 2411  const YEAR = DAY * 36512
13  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 %= MINUTE21
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

codewars

string

Sep 17, 2022

## Previous Post

LeetCode: Sum of Digits of String After Convert

Sep 15, 2022

Solving a problem in one go is such a good feeling

Search Posts