Skip to content

Commit 5d38ba8

Browse files
committed
Add task for error handling
1 parent 97443b0 commit 5d38ba8

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

JavaScript/Tasks/5-errors.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
'use strict';
2+
3+
// Task: rewrite error handling to use callback-last-error-first
4+
// contract to return errors instead of throwing them.
5+
// So remove all try/catch blocks and pass errors to callbacks.
6+
// Hint: You may also use error.cause to wrap escalated errors.
7+
// Extra credit task: use AggregateError to combine escalated errors.
8+
// Extra credit task: fix eslint error: "Function declared in a loop
9+
// contains unsafe references to variable(s) 'total' no-loop-func"
10+
11+
const MAX_PURCHASE = 2000;
12+
13+
const calculateSubtotal = (goods, callback) => {
14+
let amount = 0;
15+
for (const item of goods) {
16+
if (typeof item.name !== 'string') {
17+
throw new Error('Noname in item in the bill');
18+
}
19+
if (typeof item.price !== 'number') {
20+
throw new Error(`${item.name} price expected to be number`);
21+
}
22+
if (item.price < 0) {
23+
throw new Error(`Negative price for ${item.name}`);
24+
}
25+
amount += item.price;
26+
}
27+
callback(amount);
28+
};
29+
30+
const calculateTotal = (order, callback) => {
31+
const expenses = new Map();
32+
let total = 0;
33+
for (const groupName in order) {
34+
const goods = order[groupName];
35+
calculateSubtotal(goods, (amount) => {
36+
total += amount;
37+
expenses.set(groupName, amount);
38+
});
39+
if (total > MAX_PURCHASE) {
40+
throw new Error('Total is above the limit');
41+
}
42+
}
43+
return callback({ total, expenses });
44+
};
45+
46+
const purchase = {
47+
Electronics: [
48+
{ name: 'Laptop', price: 1500 },
49+
{ name: 'Keyboard', price: 100 },
50+
{ name: 'HDMI cable' },
51+
],
52+
Textile: [
53+
{ name: 'Bag', price: 50 },
54+
{ price: 20 },
55+
],
56+
};
57+
58+
try {
59+
console.log(purchase);
60+
calculateTotal(purchase, (bill) => {
61+
console.log(bill);
62+
});
63+
} catch (error) {
64+
console.log('Error detected');
65+
console.error(error);
66+
}

0 commit comments

Comments
 (0)