Dev Helpers
← Back

Count occupied product slots per bin

Count occupied product slots per bin. 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 = Object.fromEntries(
  [...new Set(rows.map((r) => r.bin))].map((bin) => [
    bin,
    rows.filter((r) => r.bin === bin && r.qty > 0).length,
  ]),
);
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "A": 2,
  "B": 1
}