Parse and Format Durations

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write parseDuration(text), which turns text like "1h 30m 15s" into a number of seconds (5415 here). The text is one or more parts, each a whole number written directly before its unit: d for days, h for hours, m for minutes, s for seconds, in lower case. Parts may come in any order, each unit at most once, separated by any number of spaces or by none ("2d4h" is fine), with spaces allowed around the whole text. A number may be bigger than its unit, so "90m" is 5400. Return null for anything else: empty text, a number without a unit or a unit without a number, a space between a number and its unit, decimals, minus signs, unknown units or a repeated unit. Then write formatDuration(seconds), which takes a whole number of seconds, zero or more, and returns it in days, hours, minutes and seconds, biggest first, leaving out the units that are zero and separating the parts with one space, such as "1d 1h 1m 1s" or "2h". Zero is "0s".

Your code must pass

  • Parses each unit
  • Adds up several parts, with or without spaces
  • Returns null for text that isn't a duration
  • Formats seconds biggest unit first
  • Formats zero as 0s
  • Formats and parses back to the same seconds