Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 42 lines · 1.2 KiB · at 2cc04ee

export class DurationError extends Error {  constructor(    public readonly kind: "invalid_duration",    public readonly input: string,  ) {    super(`${kind}: ${input}`);  }}// Index is the unit's rank: larger units first.const UNIT_MS = [86400000, 3600000, 60000, 1000, 1];const isDigit = (c: string): boolean => c.length === 1 && c >= "0" && c <= "9";/** Returns milliseconds. Throws DurationError when text is not a valid duration. */export function parseDuration(text: string): number {  const fail = () => new DurationError("invalid_duration", text);  if (text.length === 0) throw fail();  let i = 0;  let lastRank = -1;  let total = 0;  while (i < text.length) {    const start = i;    while (i < text.length && isDigit(text.charAt(i))) i++;    if (i === start) throw fail();    const amount = Number(text.slice(start, i));    let rank: number;    if (text.startsWith("ms", i)) {      rank = 4;      i += 2;    } else {      const c = text.charAt(i);      rank = c.length === 1 ? "dhms".indexOf(c) : -1;      if (rank < 0) throw fail();      i += 1;    }    if (rank <= lastRank) throw fail();    lastRank = rank;    total += amount * UNIT_MS[rank];  }  return total;}