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.

392 lines (390 loc) • 13.6 kB
import { coalesceIntervalNanoseconds } from "./intervalNanoseconds.js"; // src/internal/dutyRunIndex.ts const length = (run) => run.end - run.start; /** Binary-search steps: an array holds under 2^32 elements. */ const SEARCH_STEPS = 33; /** * The first position in `[0, count)` where `holds` is true, given it is false and then true; `count` * when it never is. */ function firstWhere(count, holds) { let low = 0; let high = count; for (let step = 0; step < SEARCH_STEPS && low < high; step++) { const middle = low + high >> 1; if (holds(middle)) high = middle; else low = middle + 1; } return low; } /** The first position in `[0, limit)` whose value is at least `target`, in ascending values. */ function lowerBound(values, target, limit = values.length) { return firstWhere(limit, (position) => values[position] >= target); } /** Maximal runs of touching entries passing `matches`, merged as `mergeIntervals` merges them. */ function runsMatching(entries, matches) { return coalesceIntervalNanoseconds(entries.filter((entry) => matches(entry.status)).map(({ start, end }) => ({ start, end, startText: "", endText: "" }))).map(({ start, end }) => ({ start, end })); } /** The index of a log's entries under a test. */ function buildIndex(store, matches) { const { entries } = store; const matched = entries.map((entry) => matches(entry.status)); const entryPrefix = [0n]; let total = 0n; for (let position = 0; position < entries.length; position++) { const entry = entries[position]; if (matched[position]) total += entry.end - entry.start; entryPrefix.push(total); } const runs = runsMatching(entries, matches); return { entries, entryStarts: store.entryStarts, matched, entryPrefix, runs, runStarts: runs.map((run) => run.start), runEnds: runs.map((run) => run.end), qualifying: /* @__PURE__ */ new Map(), events: /* @__PURE__ */ new Map(), interruptions: /* @__PURE__ */ new Map(), pairTables: /* @__PURE__ */ new Map() }; } /** * A call's store: the entries and, as tests ask for them, an index of each. * * @param entries the parsed log, ordered and separate */ function createRunStore(entries) { return { entries, entryStarts: entries.map((entry) => entry.start), positive: /* @__PURE__ */ new Map(), complement: /* @__PURE__ */ new Map(), nextMatch: /* @__PURE__ */ new Map() }; } /** * The index of a test, built on first use and kept: a set or the complement of one is keyed by its * set object, which the rules hold once per call. */ function runIndex(store, test) { if (test instanceof Set) { let known = store.positive.get(test); if (known === void 0) { known = buildIndex(store, (status) => test.has(status)); store.positive.set(test, known); } return known; } const { not, within = null } = test; let byWithin = store.complement.get(not); if (byWithin === void 0) { byWithin = /* @__PURE__ */ new Map(); store.complement.set(not, byWithin); } let known = byWithin.get(within); if (known === void 0) { known = buildIndex(store, (status) => !not.has(status) && (within === null || within.has(status))); byWithin.set(within, known); } return known; } /** Time in the test over `[-∞, t)`, whole entries by prefix and the entry holding `t` by part. */ function cumulative(index, t) { const taken = lowerBound(index.entryStarts, t); if (taken === 0) return 0n; const entry = index.entries[taken - 1]; const prefix = index.entryPrefix[taken - 1]; return index.matched[taken - 1] ? prefix + ((entry.end < t ? entry.end : t) - entry.start) : prefix; } /** * Time in the test inside `[from, to)` of the log as it stood at `at`: entries starting at or after * `at` are gone and the one straddling it ends there. * * @example timeInBefore(index, 0n, 100n, 10n) // time in the test inside [0, 10) */ function timeInBefore(index, from, to, at) { const upper = to < at ? to : at; return upper > from ? cumulative(index, upper) - cumulative(index, from) : 0n; } /** The runs of the log as it stood at `at`: no copy, the last cut there. */ function runsUntil(index, at) { const count = lowerBound(index.runStarts, at); const run = count > 0 ? index.runs[count - 1] : void 0; return { index, count, last: run !== void 0 && run.end > at ? { start: run.start, end: at } : run }; } /** The `position`-th run of a view, the last one cut. */ function viewRun(view, position) { return position === view.count - 1 ? view.last : view.index.runs[position]; } /** The first position in a view whose run ends after `t`; the view's count when none does. */ function firstEndingAfter(view, t) { return firstWhere(view.count, (position) => viewRun(view, position).end > t); } /** The first position in a view whose run starts at or after `t`; the view's count when none. */ function firstStartingAtOrAfter(view, t) { return lowerBound(view.index.runStarts, t, view.count); } /** For each run, the index of the latest run up to it of at least `minimum`, or -1. */ function qualifyingAt(index, minimum) { let known = index.qualifying.get(minimum); if (known === void 0) { const found = []; let latest = -1; for (let position = 0; position < index.runs.length; position++) { if (length(index.runs[position]) >= minimum) latest = position; found.push(latest); } known = found; index.qualifying.set(minimum, known); } return known; } /** * The latest of a view's first `taken` runs that is at least `minimum` long. The view's last run * counts at its cut length. */ function latestAtLeast(view, taken, minimum) { let whole = taken - 1; if (taken === view.count && view.last !== void 0) { if (length(view.last) >= minimum) return view.last; whole = taken - 2; } const position = whole < 0 ? -1 : qualifyingAt(view.index, minimum)[whole]; return position < 0 ? void 0 : view.index.runs[position]; } /** The latest run in a view at least `minimum` long. */ function lastAtLeastUntil(view, minimum) { return latestAtLeast(view, view.count, minimum); } /** How many of a view's first runs end at or before `t`. */ function endingAtOrBefore(view, t) { return firstEndingAfter(view, t); } /** The run of a view that ends at `t`, if one does. */ function runEndingAt(view, t) { const position = firstEndingAfter(view, t - 1n); if (position >= view.count) return; const run = viewRun(view, position); return run.end === t ? run : void 0; } function eventsOf(index, minimum, maximum) { const key = `${minimum}:${maximum ?? ""}`; let known = index.events.get(key); if (known === void 0) { const indexes = []; const starts = []; for (let position = 0; position < index.runs.length; position++) { const run = index.runs[position]; const taken = length(run); if (taken >= minimum && (maximum === null || taken < maximum)) { indexes.push(position); starts.push(run.start); } } known = { indexes, starts }; index.events.set(key, known); } return known; } /** * How many of a view's runs of at least `minimum` and under `maximum` (`null`: no upper bound) * start in `[from, to)` (`null`: no upper bound). The view's last run counts at its cut length, * and not at all when it ends at `skipEndingAt`. */ function countEvents(view, bounds, range, skipEndingAt) { const { minimum, maximum } = bounds; const { from, to } = range; const list = eventsOf(view.index, minimum, maximum); const whole = lowerBound(list.indexes, view.count - 1); const low = lowerBound(list.starts, from, whole); const high = to === null ? whole : lowerBound(list.starts, to, whole); let found = high > low ? high - low : 0; const { last } = view; if (last !== void 0) { const taken = length(last); if (taken >= minimum && (maximum === null || taken < maximum) && last.start >= from && (to === null || last.start < to) && last.end !== skipEndingAt) found++; } return found; } /** The entries starting before `at`: the log's length at `at`. */ function entriesBefore(store, at) { return lowerBound(store.entryStarts, at); } /** The start of the log's first entry, when it starts before `at`. */ function logStartBefore(store, at) { const first = store.entries[0]; return first !== void 0 && first.start < at ? first.start : void 0; } /** The log's last entry as it stood at `at`, cut there. */ function lastEntryBefore(store, at) { const taken = entriesBefore(store, at); const entry = taken > 0 ? store.entries[taken - 1] : void 0; return entry !== void 0 && entry.end > at ? { ...entry, end: at } : entry; } /** The entry holding the instant `at`, if one does (start ≤ at < end). */ function entryHolding(store, at) { const taken = lowerBound(store.entryStarts, at + 1n); const entry = taken > 0 ? store.entries[taken - 1] : void 0; return entry !== void 0 && entry.end > at ? entry : void 0; } /** * The first entry in `statuses` that starts at or after `from` (`null`: any) and before `at`. */ function firstEntryIn(store, statuses, from, at) { let next = store.nextMatch.get(statuses); if (next === void 0) { const found = Array.from({ length: store.entries.length + 1 }, () => store.entries.length); for (let position = store.entries.length - 1; position >= 0; position--) found[position] = statuses.has(store.entries[position].status) ? position : found[position + 1]; next = found; store.nextMatch.set(statuses, next); } const begin = from === null ? 0 : lowerBound(store.entryStarts, from); const entry = store.entries[next[begin]]; return entry !== void 0 && entry.start < at ? entry : void 0; } /** One break applied to a required-interruption state. */ function interrupt(state, pause, minimum, split) { const taken = length(pause); if (taken >= minimum) return { resetAt: pause.end, part: 0 }; if (split !== null && taken >= split[state.part]) { const part = state.part + 1; return part === split.length ? { resetAt: pause.end, part: 0 } : { resetAt: state.resetAt, part }; } return state; } /** * Where a required-interruption count was reset, taking every break a view holds in order: a break * of `minimum` resets it, and breaks that meet `split` one after another in order reset it too. * * @returns the instant of the last reset, or null when none */ function interruptionResetAt(view, minimum, split) { const { index } = view; const key = `${minimum}|${split === null ? "" : split.join(",")}`; let states = index.interruptions.get(key); if (states === void 0) { const resetAt = []; const part = []; let state = { resetAt: null, part: 0 }; for (const pause of index.runs) { state = interrupt(state, pause, minimum, split); resetAt.push(state.resetAt); part.push(state.part); } states = { resetAt, part }; index.interruptions.set(key, states); } if (view.last === void 0) return null; const before = view.count - 2; return interrupt(before < 0 ? { resetAt: null, part: 0 } : { resetAt: states.resetAt[before], part: states.part[before] }, view.last, minimum, split).resetAt; } /** Whether two rests of these lengths, in a row and each over the floor, are a pair. */ function qualifies(pair, earlier, later) { return (earlier > later ? earlier : later) >= pair.one && earlier + later >= pair.combined; } /** The pairs of the whole log for these floors, as `restPairs` finds them, built once. */ function pairTableOf(index, fullRest, pair) { const key = `${fullRest}|${pair.each}|${pair.one}|${pair.combined}`; const pairs = (earlier, taken) => qualifies(pair, earlier, taken); let known = index.pairTables.get(key); if (known === void 0) { const seconds = []; const firsts = []; const previous = []; let before = -1; for (const [position, run] of index.runs.entries()) { const taken = length(run); previous.push(before); if (taken >= fullRest) before = -1; else if (taken >= pair.each) { if (before >= 0 && pairs(length(index.runs[before]), taken)) { seconds.push(position); firsts.push(before); } before = position; } } known = { seconds, firsts, previous }; index.pairTables.set(key, known); } return known; } /** * The latest rest pair among a view's runs from `from` on: what the last of * `restPairs(viewRunsFrom(view, from), fullRest, pair)` is, without walking the runs. Only the * view's last run is cut, so it is tried by itself and every earlier pair comes from the whole-log * table. */ function latestPairFrom(view, from, fullRest, pair) { const { index, count, last } = view; if (count === 0 || last === void 0) return; const table = pairTableOf(index, fullRest, pair); const taken = length(last); const before = table.previous[count - 1]; if (taken < fullRest && taken >= pair.each && before >= from) { const earlier = index.runs[before]; if (qualifies(pair, length(earlier), taken)) return { first: earlier, second: last }; } const found = firstWhere(table.seconds.length, (k) => table.seconds[k] >= count - 1) - 1; return found >= 0 && table.firsts[found] >= from ? { first: index.runs[table.firsts[found]], second: index.runs[table.seconds[found]] } : void 0; } /** How many of the ascending values are in `[low, high)`. */ function countInRange(sorted, low, high) { return high > low ? lowerBound(sorted, high) - lowerBound(sorted, low) : 0; } export { countEvents, countInRange, createRunStore, endingAtOrBefore, entryHolding, firstEndingAfter, firstEntryIn, firstStartingAtOrAfter, firstWhere, interruptionResetAt, lastAtLeastUntil, lastEntryBefore, latestAtLeast, latestPairFrom, logStartBefore, runEndingAt, runIndex, runsMatching, runsUntil, timeInBefore, viewRun };