Dev Helpers
← Back

Select the reading nearest a target

Select the reading nearest a target. 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([
  '{"site":"N","hour":8,"value":12}\n',
  '{"site":"S","hour":8,"value":17}\n',
  '{"site":"N","hour":9,"value":15}\n',
  '{"site":"S","hour":9,"value":14}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
  rows.push(JSON.parse(line));
}
const result = rows.toSorted(
  (a, b) => Math.abs(a.value - 16) - Math.abs(b.value - 16),
)[0];
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "site": "S",
  "hour": 8,
  "value": 17
}