UNPKG

@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.

512 lines (511 loc) • 18 kB
// src/internal/rangeDetector.ts const MIN = 6e4; const HR = 60 * MIN; const DY = 24 * HR; const LIMIT = { y: Infinity, G: Infinity, M: 367 * DY, d: 32 * DY, a: DY, B: DY, h: DY, m: 61 * MIN }; /** * The fixed probe pairs, as UTC epoch milliseconds (literals: nothing here runs at import): the * largest field that differs is year, month, day, day period, hour, minute, year, day. */ const PROBES = [ [ "y", 17157795e5, 17636568e5 ], [ "M", 17157795e5, 17189016e5 ], [ "d", 17157795e5, 1715964e6 ], [ "a", 17157651e5, 17157912e5 ], [ "h", 17157795e5, 17157912e5 ], [ "m", 17157795e5, 17157804e5 ], [ "y", 17206221e5, 17521581e5 ], [ "d", 17206221e5, 17207949e5 ] ]; /** * The probe pairs of a formatter that prints a flexible day period, all inside one AM/PM half. A * pair is `B` when the two times print different day periods and `h` when they print one * (ECMA-402 Table 6), decided per formatter, as day-period rules are per locale: 01:25 to 02:40 * and 13:25 to 14:40 are one period in every locale that has them, 12:25 to 18:40 and 00:10 to * 06:45 cross a period boundary in each. 12:00 to 12:25 is the pair a pattern with minutes prints * as `noon` and `in the afternoon` (en), so a range that keeps only the end's period drops the * start's; where both print one period the pair is `h` and passes. */ const PERIOD_PROBES = [ [ "h", 17157363e5, 17157408e5 ], [ "h", 17157795e5, 1715784e6 ], [ "B", 17157759e5, 17157984e5 ], [ "B", 17157318e5, 17157555e5 ], [ "B", 17157744e5, 17157759e5 ] ]; /** * The pairs at the hour that wraps (00:10 and 12:10 with their 02:40 and 14:40): a 12-hour cycle * prints that hour as 12, and a range pattern may print 0. Only the number is compared * (`droppedNumber`), never a word, as a range may name a finer day period (zh `凌晨12:10至2:40` * for the single's `上午12:10`). */ const WRAP_PROBES = [[ "h", 17157318e5, 17157408e5 ], [ "h", 1715775e6, 1715784e6 ]]; /** The era pairs: Heisei to Reiwa in the japanese calendar, and BC to AD in the others. */ const ERA_PROBES = { japanese: [ "G", 14681613e5, 15943917e5 ], other: [ "G", -653064243e5, 17521581e5 ] }; /** Minute; hour; day period; day and weekday; day only; month; year; one sexagenary cycle; hour back. */ const MOVES = [ MIN, 61 * MIN, 4 * HR, 9006e4, 7 * DY, 276846e4, 3171246e4, 21915 * DY, -61 * MIN ]; const SPLIT = { "0": "8", "1": "8", "2": "8", "3": "4", "6": "7" }; const NUMBER = /\p{Nd}/u; const LAT = `${String.raw`(?:\p{sc=Latin}|(?=\p{L})\p{sc=Zyyy})`}${String.raw`(?:\p{sc=Latin}|\p{M}|(?=\p{L})\p{sc=Zyyy})`}*`; const OTH = String.raw`(?:(?![\p{sc=Latin}\p{sc=Zyyy}])[\p{L}\p{M}])+`; const JOIN = String.raw`(?:(?![‐-―−〜~~\//])\p{P})+`; const RUN = new RegExp(String.raw`\p{Nd}+|${LAT}(?:${JOIN}${LAT})*|${OTH}(?:${JOIN}${OTH})*`, "gu"); const DASH = /[‐-―−〜~~-]/u; /** The digit zero of the run of ten digits that holds `cp`. */ function zeroOf(cp) { let zero = cp; while (zero > 0 && NUMBER.test(String.fromCodePoint(zero - 1)) && cp - (zero - 1) < 10) zero--; return zero; } /** The ASCII digits of a number written in any numbering system. */ function ascii(text) { return [...text].map((ch) => { const cp = ch.codePointAt(0) ?? 0; return (cp - zeroOf(cp)) % 10; }).join(""); } /** The runs of a text: a number is `#value` (so `05` and `5` are one value), a word is itself. */ function rangeRuns(text) { return [...text.matchAll(RUN)].map((m) => NUMBER.test(m[0]) ? `#${Number(ascii(m[0]))}` : m[0]); } /** The text before each run. */ function gaps(text) { let end = 0; return [...text.matchAll(RUN)].map((m) => { const gap = text.slice(end, m.index); end = m.index + m[0].length; return gap; }); } /** The separators between adjacent numbers, joined. */ function numberSeparators(text) { const all = [...text.matchAll(RUN)]; const out = []; for (let i = 1; i < all.length; i++) { const prev = all[i - 1]; const next = all[i]; if (prev && next && NUMBER.test(prev[0]) && NUMBER.test(next[0])) out.push(text.slice(prev.index + prev[0].length, next.index).replace(/\s+/gu, "")); } return out.join("\0"); } const kinds = (toks) => toks.map((t) => t.startsWith("#") ? "d" : "w").join(""); /** A word that takes its neighbour's signature (a word of a name next to a word that changes). */ function joinNames(toks, sigs, gp) { const was = [...sigs]; const sub = (x, y) => x.length < y.length && [...x].every((j) => y.includes(j)); const spaced = (q, d) => /^\s+$/u.test(gp[Math.max(q, q - d)] ?? ""); toks.forEach((t, p) => { if (!was[p] || t.startsWith("#")) return; for (const d of [-1, 1]) { let q = p + d; while (q >= 0 && q < toks.length && !toks[q]?.startsWith("#") && spaced(q, d) && !was[q]) q += d; if (q >= 0 && q < toks.length && !toks[q]?.startsWith("#") && spaced(q, d) && sub(was[p] ?? "", was[q] ?? "")) { sigs[p] = was[q] ?? ""; break; } } }); } /** The memoised calls of one verdict. */ var Calls = class { memo = /* @__PURE__ */ new Map(); source; constructor(source) { this.source = source; } format(t) { const key = `f${t}`; let text = this.memo.get(key); if (text === void 0) { text = this.source.format(t); this.memo.set(key, text); } return text; } range(a, b) { const key = `${a},${b}`; let text = this.memo.get(key); if (text === void 0) { text = this.source.formatRange(a, b); this.memo.set(key, text); } return text; } }; /** Per position of the single and of the range, the moves that change it. */ function family(calls, range, single, limit, singleAt, rangeAt, other) { const r0 = rangeRuns(range); const s0 = rangeRuns(single); const kr = kinds(r0); const ks = kinds(s0); const fallback0 = other !== void 0 && range.includes(single) && range.includes(other); const rs = r0.map(() => ""); const rv = r0.map(() => ""); const ss = s0.map(() => ""); const sv = s0.map(() => ""); const rok = []; const ok = []; MOVES.forEach((m, j) => { const x = rangeAt(m); if (Math.abs(m) >= limit || !(x[0] < x[1])) return; const single1 = calls.format(singleAt(m)); const s1 = rangeRuns(single1); const same = kinds(s1) === ks; s0.forEach((t, p) => { if (same ? s1[p] !== t : !s1.includes(t)) sv[p] += j; }); const range1 = calls.range(x[0], x[1]); if (other !== void 0 && !fallback0 && range1.includes(single1) && range1.includes(other)) return; const r1 = rangeRuns(range1); if (kinds(r1) !== kr || numberSeparators(range1) !== numberSeparators(range)) return; rok.push(j); r0.forEach((t, p) => { if (r1[p] !== t) rv[p] += j; }); if (!same) return; const dS = s0.filter((t, p) => s1[p] !== t).length; if (other !== void 0 && dS && r0.filter((t, p) => r1[p] !== t).length > 2 * dS + 1) return; ok.push(j); r0.forEach((t, p) => { if (r1[p] !== t) rs[p] += j; }); s0.forEach((t, p) => { if (s1[p] !== t) ss[p] += j; }); }); const gp = gaps(single); s0.forEach((t, p) => { if (ss[p] !== "7" || t.startsWith("#")) return; for (const q of [p - 1, p + 1]) { const between = gp[Math.max(p, q)] ?? ""; if (q >= 0 && q < s0.length && !s0[q]?.startsWith("#") && ss[q] && /^[\s\p{P}]*$/u.test(between) && !NUMBER.test(between)) { ss[p] = ss[q] ?? ""; break; } } }); const rs0 = [...rs]; joinNames(s0, ss, gp); joinNames(r0, rs, gaps(range)); const key = (toks, g) => toks.map((t, p) => t.startsWith("#") && p > 0 && g[p] === "" && !toks[p - 1]?.startsWith("#") ? `${toks[p - 1]}\u0001${t}` : t); return { r0, s0, rs, rs0, rv, rok: rok.join(""), ss, sv, ok: ok.join(""), sk: key(s0, gp), rk: key(r0, gaps(range)) }; } /** The class of a position: the first move that changes it, plus one splitting move for that level. */ function classOf(sig, ok) { if (!sig) return ""; const first = sig[0] ?? ""; const split = SPLIT[first]; return first + (split && ok.includes(split) ? sig.includes(split) ? "+" : "-" : ""); } function groups(toks, sigs, ok, keep) { const g = /* @__PURE__ */ new Map(); toks.forEach((t, p) => { const c = classOf(sigs[p] ?? "", ok); if (c && keep(p)) { const list = g.get(c) ?? []; list.push(t); g.set(c, list); } }); return g; } /** A range word holds the single's word: equal, beginning with a one-letter form, or containing a longer one. */ function holds(u, t) { const upper = u.toLocaleLowerCase(); const lower = t.toLocaleLowerCase(); return [...lower].length > 1 ? upper.includes(lower) : upper.startsWith(lower); } const isWord = (t) => t !== void 0 && !t.startsWith("#"); /** Whether a number of the single is missing, wrong or repeated in the range, class by class. */ function judge(F, judging = {}) { const keep = judging.keep ?? (() => true); const shared = judging.shared ?? false; const fresh = judging.fresh ?? (() => false); const apart = judging.apart ?? (() => false); const S = groups(F.s0, F.ss, F.ok, keep); const R = groups(F.r0, F.rs, F.ok, () => true); const SK = groups(F.sk, F.ss, F.ok, keep); const RK = groups(F.rk, F.rs, F.ok, () => true); for (const [c, ts] of S) { const r = R.get(c); const sup = (p, sig) => [...F.ss[p] ?? ""].every((j) => sig.includes(j)); const finer = () => F.s0.every((t, p) => classOf(F.ss[p] ?? "", F.ok) !== c || !keep(p) || isWord(t) && F.r0.some((u, q) => holds(u, t) && sup(p, F.rs[q] ?? "") || q > 0 && `${F.r0[q - 1]}${u}` === t && sup(p, `${F.rs[q - 1]}${F.rs[q]}`))); const own = () => F.r0.some((u, q) => isWord(u) && !F.s0.includes(u) && classOf(F.rs0[q] ?? "", F.ok) === c); const merged = (ws) => ws.every((t) => F.r0.includes(t) && (judging.other ?? []).includes(t)); if (!r) { if (ts.every(isWord) && (fresh(ts) || finer() || own() || merged(ts))) continue; return true; } const kd = (u) => new Set(u.map((t) => t.startsWith("#"))).size; if (!shared && /^([012]|3$)/.test(c) && kd(ts) === 2 && kd(r) < 2) return true; const sn = ts.filter((t) => t.startsWith("#")).map((t) => String(Number(t.slice(1)))); const rn = r.filter((t) => t.startsWith("#")).map((t) => String(Number(t.slice(1)))); if (sn.length && rn.length && !rn.some((x) => sn.some((y) => y.includes(x) || x.includes(y)))) return true; const tk = SK.get(c) ?? []; const rk = RK.get(c) ?? []; const at = (t) => F.rk.flatMap((u, q) => u === t && classOf(F.rs[q] ?? "", F.ok) === c ? [q] : []); const count = (list, t) => list.filter((u) => u === t).length; if (!shared && tk.some((t) => count(rk, t) > count(tk, t) && !apart(at(t)))) return true; } return false; } /** Whether a word or number of the single is in no word of the range, and the range has no stand-in for it. */ function isAbsent(F, O, known, sameShape, shared, half) { const rescue = F.r0.some((t, q) => isWord(t) && !known.has(t) && !O.rs[q]); const num = (p) => F.r0.some((t, q) => !isWord(t) && !known.has(t) && !O.rv[q] && [...F.sv[p] ?? ""].every((j) => !F.rok.includes(j) || (F.rv[q] ?? "").includes(j))); for (let p = 0; p < F.s0.length; p++) { const t = F.s0[p] ?? ""; const theirs = O.s0[p] ?? ""; if (isWord(t) && isWord(theirs) && !F.sv[p] && !F.ss[p] && sameShape && !shared(p) && !F.r0.some((u) => u === t || holds(u, t)) && F.r0.some((u, q) => u === theirs && (!O.ss[p] || classOf(O.rs[q] ?? "", F.ok) === classOf(O.ss[p] ?? "", F.ok))) && !half.some((u) => isWord(u) && !known.has(u))) return true; if (F.sv[p] && !F.ss[p] && !(sameShape && shared(p)) && !F.r0.some((u) => u === t || isWord(t) && holds(u, t)) && !rescue && !num(p)) return true; } return false; } /** * Whether each date's own fields stay on its own side of the joiner: the range is cut at a dash * and every run only the start prints is left of it, every run only the end prints is right of it (a run may also sit on the other side, as a literal of the pattern repeats there). * A range with no dash has no joiner to check, and a range that prints a run neither date prints * is left to the other checks: a value that only one date's own run happens to equal there cannot * tell which side it belongs to. */ function isOrdered(range, first, last) { if (!DASH.test(range)) return true; const own = (x, y) => { const other = new Set(rangeRuns(y)); return rangeRuns(x).filter((t) => !other.has(t)); }; const a = own(first, last); const b = own(last, first); if (!a.length || !b.length) return true; const all = [...range.matchAll(RUN)]; const toks = rangeRuns(range); const printed = /* @__PURE__ */ new Set([...rangeRuns(first), ...rangeRuns(last)]); if (toks.some((t) => !printed.has(t))) return true; const count = (text, ch) => text.split(ch).length - 1; const cuts = [...range.matchAll(new RegExp(DASH.source, "gu"))].filter((m) => count(range, m[0]) > count(first, m[0]) + count(last, m[0])).map((m) => m.index); if (!cuts.length) return true; return cuts.some((cut) => { const left = new Set(toks.filter((_, i) => (all[i]?.index ?? 0) < cut)); const right = new Set(toks.filter((_, i) => (all[i]?.index ?? 0) > cut)); return a.every((t) => left.has(t)) && b.every((t) => right.has(t)); }); } /** Whether a range is the start's single, a short joiner with no digit, and the end's single. */ function isJoined(range, first, last) { const gap = range.length - first.length - last.length; return gap >= 0 && gap <= 6 && range.startsWith(first) && range.endsWith(last) && !NUMBER.test(range.slice(first.length, range.length - last.length)); } /** * Whether a formatter's `formatRange` drops an endpoint's field, prints one twice, prints another * value for one, or puts a date's field on the other date's side. * * @param source `format` and `formatRange` of one formatter (a UTC clone, no zone moves a pattern) * @param calendar the formatter's calendar, which chooses the era probe pair * @returns the verdict * * @example rangeVerdict(new Intl.DateTimeFormat("en", { dateStyle: "medium", timeZone: "UTC" }), "gregory") // { flagged: false } */ function rangeVerdict(source, calendar) { const calls = new Calls(source); const cyclic = calendar === "chinese" || calendar === "dangi"; const period = source.dayPeriod?.bind(source); const probes = [ ...PROBES, ...period ? PERIOD_PROBES : [], calendar === "japanese" ? ERA_PROBES.japanese : ERA_PROBES.other ]; const classes = /* @__PURE__ */ new Set(); let kind; for (const [probe, a, b] of probes) { const g = period && (probe === "h" || probe === "B") ? period(a) === period(b) ? "h" : "B" : probe; const found = probeKind(calls, cyclic, g, a, b) ?? (period && droppedPeriod(calls, period, a, b)); if (found) { classes.add(g); kind ??= found; } } for (const [, a, b] of WRAP_PROBES) if (droppedNumber(calls, a, b)) { const g = period && period(a) !== period(b) ? "B" : "h"; classes.add(g); kind ??= "number"; } return classes.size ? { flagged: true, kind, classes: [...classes] } : { flagged: false, classes: [] }; } /** * Whether the range writes the hour 0 of a 12-hour cycle as `0` where the single writes `12` (a * range may keep a number both dates share, never change one: ja `夜中0:10` for `夜中12:10`). Only * the digit groups of value twelve are read, so a zone offset or a date field never decides. */ function droppedNumber(calls, a, b) { const twelve = (text) => (text.match(/\p{Nd}+/gu) ?? []).some((n) => Number.parseInt(n, 10) === 12); return [a, b].some((date) => twelve(calls.format(date))) && !twelve(calls.range(a, b)); } /** * `"period"` when both singles print a flexible day period and the range prints no word of either * (a range may print the one period both times share once, or in another width: bn `দুপুর` for the * single's `দুপুরবেলায়`; never none: UTS #35 Part 4 builds each date's part from its single * pattern). */ function droppedPeriod(calls, period, a, b) { const printed = [a, b].flatMap((date) => { const text = period(date); return text !== "" && calls.format(date).includes(text) ? rangeRuns(text).filter(isWord) : []; }); const words = rangeRuns(calls.range(a, b)).filter(isWord); return printed.length === 0 || printed.some((t) => words.some((w) => t.startsWith(w) || w.startsWith(t))) ? void 0 : "period"; } /** The reason one probe pair's range is wrong, or `undefined` when it holds every field. */ function probeKind(calls, cyclic, g, a, b) { const R = calls.range(a, b); const sa = calls.format(a); const sb = calls.format(b); if (R === sa) return; if (!cyclic && isJoined(R, sa, sb)) return; if (!isOrdered(R, sa, sb)) return "order"; const limit = LIMIT[g] ?? Infinity; const FA = family(calls, R, sa, limit, (m) => a - m, (m) => [a - m, b], sb); const FB = family(calls, R, sb, limit, (m) => b + m, (m) => [a, b + m], sa); const known = /* @__PURE__ */ new Set([...FA.s0, ...FB.s0]); const low = (t) => t.toLocaleLowerCase(); const fresh = (F, O) => (ts) => F.r0.some((t, q) => isWord(t) && !known.has(t) && !O.rs[q] && ts.some((u) => u !== t && low(u).startsWith(low(t)))); const kr = kinds(rangeRuns(R)); const apart = (qs) => MOVES.some((m) => { const r1 = rangeRuns(calls.range(a - m, b - m)); return kinds(r1) === kr && new Set(qs.map((q) => r1[q])).size > 1; }); if (judge(FA, { fresh: fresh(FA, FB), apart, other: FB.s0 })) return "a"; if (judge(FB, { fresh: fresh(FB, FA), apart, other: FA.s0 })) return "b"; const cut = R.search(DASH); const halves = cut < 0 ? [rangeRuns(R), rangeRuns(R)] : [rangeRuns(R.slice(0, cut)), rangeRuns(R.slice(cut))]; const same = kinds(FA.s0) === kinds(FB.s0); const shared = (p) => same && FA.s0[p] === FB.s0[p]; if (isAbsent(FA, FB, known, same, shared, halves[0]) || isAbsent(FB, FA, known, same, shared, halves[1])) return "absent"; if (judge(family(calls, R, sa, Infinity, (m) => a - m, (m) => [a - m, b - m]), { keep: (p) => !FA.ss[p] && (!FA.sv[p] || shared(p)), shared: true })) return "both"; } export { rangeRuns, rangeVerdict };