Duration Parser For Human Time Strings
Parse compact durations such as 1h30m, 500ms or 2.5s into milliseconds with unit validation and clear syntax errors.
Code
const UNITS: Readonly<Record<string, number>> = {
ms: 1,
s: 1_000,
m: 60_000,
h: 3_600_000,
d: 86_400_000,
w: 604_800_000,
};
export function parseDuration(input: string): number {
if (typeof input !== "string") throw new TypeError("input must be a string");
const text = input.trim().toLowerCase();
if (text === "") throw new SyntaxError("duration must not be empty");
if (text.startsWith("-") || text.startsWith("+")) {
throw new RangeError("signed durations are not supported");
}
const pattern = /(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)/g;
let total = 0;
let lastIndex = 0;
let matched = false;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
const gap = text.slice(lastIndex, match.index);
if (gap.trim() !== "") throw new SyntaxError("invalid duration: " + input);
const amount = Number(match[1]);
const unit = match[2];
total += amount * (UNITS[unit] ?? 0);
lastIndex = pattern.lastIndex;
matched = true;
}
if (!matched || text.slice(lastIndex).trim() !== "") {
throw new SyntaxError("invalid duration: " + input);
}
if (!Number.isFinite(total)) throw new RangeError("duration is too large");
return Math.round(total);
}What the code does
Count the function parseDuration as the entire surface area of Duration Parser For Human Time Strings.
Repetition is confined to while ((match = pattern.exec(text)) !== null) — the rest of the file is straight-line. TypeError, SyntaxError and RangeError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
typeof input !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export function parseDuration(input: string)
Treat parseDuration as the API: import it, and ignore the supporting code.
Statements that matter
total += amount * (UNITS[unit] ?? 0);
if (typeof input !== "string") throw new TypeError("input must be a string");
if (gap.trim() !== "") throw new SyntaxError("invalid duration: " + input);
Interactive Tools for This Topic
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.
FAQ
- What happens if the preconditions do not hold?
- Validation comes first — `TypeError`, `SyntaxError` and `RangeError` marks the failure at `typeof input !== "string"`, before any partial work happens.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `parseDuration` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.