Dev Helpers
← Back

Simulate moving two pens between bins

Simulate moving two pens between bins. 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([
  '{"sku":"pen","bin":"A","qty":4}\n',
  '{"sku":"pad","bin":"B","qty":0}\n',
  '{"sku":"pen","bin":"B","qty":3}\n',
  '{"sku":"clip","bin":"A","qty":9}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
  rows.push(JSON.parse(line));
}
const result = rows.map((r) =>
  r.sku !== "pen" ? r : { ...r, qty: r.qty + (r.bin === "A" ? -2 : 2) },
);
console.log(JSON.stringify(result, null, 2));

Sample output

[
  {
    "sku": "pen",
    "bin": "A",
    "qty": 2
  },
  {
    "sku": "pad",
    "bin": "B",
    "qty": 0
  },
  {
    "sku": "pen",
    "bin": "B",
    "qty": 5
  },
  {
    "sku": "clip",
    "bin": "A",
    "qty": 9
  }
]