Functional Weave
Code in Python

monitor.series-window@1.0.0

impl/typescript.ts

1,083 bytes · the TypeScript implementation · view raw

import { type MetricSample } from "./monitor_series_window_types.ts";

/**
 * The samples with from <= at < to. Half-open, so consecutive windows
 * (the last hour, the hour before) never count a sample twice.
 */
export function seriesWindow(samples: readonly MetricSample[], from: number, to: number): readonly MetricSample[] {
  if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)) throw new RangeError("from and to must be whole seconds");
  if (from > to) throw new RangeError(`from must not be after to: ${from} > ${to}`);
  const out: MetricSample[] = [];
  for (let i = 0; i < samples.length; i++) {
    // Checked over the whole series, not just the window: a misordered store
    // gives wrong answers everywhere, so it should fail everywhere.
    if (i > 0 && samples[i].at <= samples[i - 1].at) {
      throw new RangeError(`samples must be in strictly ascending time order: ${samples[i].at} follows ${samples[i - 1].at}`);
    }
    if (samples[i].at >= from && samples[i].at < to) out.push({ at: samples[i].at, value: samples[i].value });
  }
  return out;
}