Drill

ProblemsTypeScript › dates

Read a duration a human typed

mediumdatesTypeScript

A config file lets people write timeouts as "1h30m" instead of counting seconds, and the loader has to turn that into a number without trusting it.

parseDuration(text: string) → int

Solve it in the editor →

Where you start

function parseDuration(text: string): number {
  
}

Worked examples

CallResult
parseDuration("1h30m")5400
parseDuration("45s")45
parseDuration("2h")7200
parseDuration("90m")5400

Hint

Scan digits, then expect exactly one unit letter. Remember which units you have already taken so order and repeats are both caught by the same check.

Reference solution in TypeScript
function parseDuration(text: string): number {
  const rank: Record<string, number> = { h: 1, m: 2, s: 3 };
  const mult: Record<string, number> = { h: 3600, m: 60, s: 1 };
  let i = 0;
  let total = 0;
  let last = 0;
  while (i < text.length) {
    let n = 0;
    let digits = 0;
    while (i < text.length && text[i] >= '0' && text[i] <= '9') {
      n = n * 10 + (text.charCodeAt(i) - 48);
      i++;
      digits++;
    }
    if (digits === 0 || i >= text.length) return -1;
    const u = text[i];
    if (rank[u] === undefined || rank[u] <= last) return -1;
    last = rank[u];
    total += n * mult[u];
    i++;
  }
  return total;
}

The same problem in another language

More dates problems in TypeScript