-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2-fix.js
49 lines (40 loc) · 1.08 KB
/
2-fix.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
45
46
47
48
49
'use strict';
// Task: prevent termination on error and fix code
// to prevent withdraw more than given limit
// Add 'buy' event handler
// Add 'done' event handler and emit it after iteration
const EventEmitter = require('node:events');
class Purchase extends EventEmitter {
constructor({ limit }) {
super();
this.items = [];
this.total = 0;
this.on('add', (item) => {
const total = this.total + item.price;
if (total > limit) {
this.emit('error', new Error('Limit reached'));
return;
}
this.total = total;
this.items.push(item);
this.emit('buy', item);
});
}
}
const wallet = { money: 1600 };
console.log({ wallet });
const purchase = new Purchase({ limit: wallet.money });
purchase.on('add', (item) => {
wallet.money -= item.price;
console.log({ item, wallet });
});
const electronics = [
{ name: 'Laptop', price: 1500 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
];
for (const item of electronics) {
purchase.emit('add', item);
}
console.log({ wallet });
console.log({ purchase });