@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
190 lines (189 loc) • 5.48 kB
JavaScript
// src/internal/humanDuration.ts
/** The single source of spellings for the reader and the writer. */
const HUMAN_DURATION_UNITS = [
{
rank: 1,
designator: "Y",
fraction: false,
symbol: "y",
spellings: [
"y",
"yr",
"yrs",
"year",
"years"
]
},
{
rank: 2,
designator: "M",
fraction: false,
symbol: "mo",
spellings: [
"mo",
"month",
"months"
]
},
{
rank: 3,
designator: "W",
fraction: false,
symbol: "w",
spellings: [
"w",
"wk",
"wks",
"week",
"weeks"
]
},
{
rank: 4,
designator: "D",
fraction: false,
symbol: "d",
spellings: [
"d",
"day",
"days"
]
},
{
rank: 5,
designator: "H",
fraction: true,
symbol: "h",
spellings: [
"h",
"hr",
"hrs",
"hour",
"hours"
]
},
{
rank: 6,
designator: "M",
fraction: true,
symbol: "m",
spellings: [
"m",
"min",
"mins",
"minute",
"minutes"
]
},
{
rank: 7,
designator: "S",
fraction: true,
symbol: "s",
spellings: [
"s",
"sec",
"secs",
"second",
"seconds"
]
},
{
rank: 8,
designator: "S",
fraction: false,
symbol: "",
spellings: [
"ms",
"millisecond",
"milliseconds"
]
}
];
/** Every spelling in the table, longest first so `ms` beats `m` (G1), escaped and joined with `|`. */
const HUMAN_DURATION_SPELLINGS = HUMAN_DURATION_UNITS.flatMap((unit) => unit.spellings).sort((a, b) => a.length !== b.length ? b.length - a.length : a < b ? -1 : 1).map((spelling) => spelling.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
/**
* One `number unit` pair. Groups: 1 integer digits, 2 fraction digits (1 to 9), 3 unit spelling.
* The spellings are built from `HUMAN_DURATION_UNITS` when the module loads; no ASCII letter may
* follow the unit. Flags `i` and `y` only: no `u` or `v`, so the unit letters and the `[a-z]`
* look-ahead stay ASCII-only (under `iu` they would match U+017F and U+212A) (G7). `\d` is ASCII
* either way.
*
* Sticky and shared: every caller must set `lastIndex` before `exec` or `test`.
*/
const HUMAN_DURATION_PAIR = new RegExp(`(\\d+)(?:\\.(\\d{1,9}))? *(${HUMAN_DURATION_SPELLINGS})(?![a-z])`, "iy");
/** The separator between pairs, tried in this order; no match is the empty separator. */
const HUMAN_DURATION_SEPARATOR = /,? +and +| +|, */iy;
const MAX_PAIRS = 8;
/** Match one pair at `cursor`; `null` unless its unit outranks `previousRank` (G2, G3). */
function readPair(text, cursor, previousRank) {
HUMAN_DURATION_PAIR.lastIndex = cursor;
const match = HUMAN_DURATION_PAIR.exec(text);
if (match === null) return null;
const spelling = match[3].toLowerCase();
const unit = HUMAN_DURATION_UNITS.find((candidate) => candidate.spellings.includes(spelling));
const fraction = match[2];
if (unit === void 0 || unit.rank <= previousRank) return null;
if (fraction !== void 0 && !unit.fraction) return null;
return {
unit,
digits: match[1],
fraction,
end: HUMAN_DURATION_PAIR.lastIndex
};
}
/** Index past the separator at `cursor`, or `cursor` itself for the empty separator. */
function skipSeparator(text, cursor) {
HUMAN_DURATION_SEPARATOR.lastIndex = cursor;
return HUMAN_DURATION_SEPARATOR.test(text) ? HUMAN_DURATION_SEPARATOR.lastIndex : cursor;
}
/**
* Read a human duration string into an ISO 8601 duration string, before Temporal sees it.
* Digits are kept as matched (no Number conversion); a fraction stays on its hour, minute or
* second for Temporal to spread. Milliseconds fold into seconds with BigInt (G5). Returns `null`
* for any string outside the grammar. The Temporal limits are not checked here.
*/
function humanDurationToIso(text) {
const sign = /^[+-]/.exec(text)?.[0] ?? "";
let cursor = sign.length;
const fields = [];
let milliseconds;
let previousRank = 0;
for (let count = 0; count < MAX_PAIRS; count++) {
const pair = readPair(text, cursor, previousRank);
if (pair === null) return null;
previousRank = pair.unit.rank;
const written = pair.fraction === void 0 ? pair.digits : `${pair.digits}.${pair.fraction}`;
if (pair.unit.rank === 8) milliseconds = written;
else fields[pair.unit.rank] = written;
if (pair.end === text.length) return buildIso(sign === "-", fields, milliseconds);
if (pair.fraction !== void 0) return null;
cursor = skipSeparator(text, pair.end);
if (cursor === text.length) return null;
}
return null;
}
/** Digit count without leading zeros; linear in the input. */
function significantLength(digits) {
let start = 0;
while (start < digits.length && digits.charCodeAt(start) === 48) start++;
return digits.length - start;
}
function buildIso(negative, fields, milliseconds) {
let seconds = fields[7];
if (milliseconds !== void 0) {
if (significantLength(seconds ?? "") > 16 || significantLength(milliseconds) > 19) return null;
const total = BigInt(seconds ?? "0") * 1000n + BigInt(milliseconds);
const rest = total % 1000n;
seconds = rest === 0n ? String(total / 1000n) : `${total / 1000n}.${String(rest).padStart(3, "0").replace(/0+$/, "")}`;
}
const date = [
"Y",
"M",
"W",
"D"
].map((designator, index) => fields[index + 1] === void 0 ? "" : `${fields[index + 1]}${designator}`).join("");
const time = (fields[5] === void 0 ? "" : `${fields[5]}H`) + (fields[6] === void 0 ? "" : `${fields[6]}M`) + (seconds === void 0 ? "" : `${seconds}S`);
return `${negative ? "-" : ""}P${date}${time === "" ? "" : `T${time}`}`;
}
export { HUMAN_DURATION_PAIR, HUMAN_DURATION_UNITS, humanDurationToIso };