Dev Helpers
← Back

Find the weighted unit price by item

Find the weighted unit price by item. 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([
  '{"item":"tea","units":2,"cents":350}\n',
  '{"item":"mug","units":1,"cents":900}\n',
  '{"item":"tea","units":3,"cents":325}\n',
  '{"item":"tin","units":2,"cents":500}\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.item))].map((item) => {
    const lines = rows.filter((r) => r.item === item);
    return [
      item,
      Math.round(
        lines.reduce((s, r) => s + r.units * r.cents, 0) /
          lines.reduce((s, r) => s + r.units, 0),
      ),
    ];
  }),
);
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "tea": 335,
  "mug": 900,
  "tin": 500
}