Dev Helpers
← Back

Clip service windows to a morning shift

Clip service windows to a morning shift. Parse newline-delimited records from a readable stream before applying the transformation.

Open this example in the interactive library

Source code

import { Readable } from "node:stream";
import { createInterface } from "node:readline";
const input = Readable.from([
  '{"line":"Red","start":8,"end":10}\n',
  '{"line":"Blue","start":9,"end":11}\n',
  '{"line":"Red","start":12,"end":15}\n',
  '{"line":"Gold","start":15,"end":16}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
  rows.push(JSON.parse(line));
}
const result = rows
  .filter((r) => r.start < 12 && r.end > 8)
  .map((r) => ({
    ...r,
    start: Math.max(8, r.start),
    end: Math.min(12, r.end),
  }));
console.log(JSON.stringify(result, null, 2));

Sample output

[
  {
    "line": "Red",
    "start": 8,
    "end": 10
  },
  {
    "line": "Blue",
    "start": 9,
    "end": 11
  }
]