okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142c-small into f-142407ea8192

main
1.2 KiB39 linesraw
1export type Window = {start: number; end: number};
2
3function checkWindow(w: Window): void {
4  if (w === null || typeof w !== "object") {
5    throw new RangeError("window must be an object");
6  }
7  const {start, end} = w;
8  if (typeof start !== "number" || typeof end !== "number") {
9    throw new RangeError("window start/end must be numbers");
10  }
11  if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) {
12    throw new RangeError("window must have finite start <= end");
13  }
14}
15
16export function mergeWindows(windows: Window[], gap = 0): Window[] {
17  if (!Array.isArray(windows)) {
18    throw new RangeError("windows must be an array");
19  }
20  if (typeof gap !== "number" || !Number.isFinite(gap) || gap < 0) {
21    throw new RangeError("gap must be a finite nonnegative number");
22  }
23  for (const w of windows) {
24    checkWindow(w);
25  }
26  const sorted = [...windows].sort(
27    (a, b) => a.start - b.start || a.end - b.end,
28  );
29  const result: Window[] = [];
30  for (const w of sorted) {
31    const last = result.at(-1);
32    if (last && w.start - last.end <= gap) {
33      if (w.end > last.end) last.end = w.end;
34    } else {
35      result.push({start: w.start, end: w.end});
36    }
37  }
38  return result;
39}