-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathb-object.js
44 lines (38 loc) · 973 Bytes
/
b-object.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use strict';
const stream = require('node:stream');
const purchase = {
Electronics: [
{ name: 'Laptop', price: -1500 },
{ name: 'Mouse', price: 25 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
],
Textile: [
{ name: 'Bag', price: 50 },
{ name: 'Mouse pad', price: 5 },
],
};
const subtotal = new stream.Transform({
writableObjectMode: true,
readableObjectMode: true,
transform({ groupName, goods }, encoding, next) {
let amount = 0;
for (const item of goods) {
if (item.price < 0) {
return void next(new Error('Negative price'));
}
amount += item.price;
}
next(null, { groupName, count: goods.length, amount });
},
});
subtotal.on('data', (data) => {
console.log(data);
});
subtotal.on('error', (error) => {
console.log(error.message);
});
for (const groupName in purchase) {
const goods = purchase[groupName];
subtotal.write({ groupName, goods });
}