Functional Weave
Code in Rust

monitor.maintenance-window@1.0.0

impl/typescript.ts

1,140 bytes · the TypeScript implementation · view raw

import { type MaintenanceWindow } from "./monitor_maintenance_window_types.ts";

/**
 * The window with start <= at < end. Half-open, so a window ending at 02:00
 * and the next starting at 02:00 never both apply. When several overlap, the
 * one that started first wins (ties: the first in the list), so the answer
 * does not depend on how the caller happened to sort them. Every window is
 * checked, not only the active ones: a backwards window is a config error
 * that would otherwise silently never apply.
 */
export function activeMaintenance(windows: readonly MaintenanceWindow[], at: number): MaintenanceWindow | null {
  if (!Number.isSafeInteger(at)) throw new RangeError(`at must be a whole second, received ${at}`);
  let best: MaintenanceWindow | null = null;
  for (const w of windows) {
    if (w.end <= w.start) {
      throw new RangeError(`maintenance window "${w.name}" must end after it starts: start ${w.start}, end ${w.end}`);
    }
    if (w.start <= at && at < w.end && (best === null || w.start < best.start)) best = w;
  }
  return best === null ? null : { name: best.name, start: best.start, end: best.end };
}