Skip to content

Commit e32af67

Browse files
committed
Add tasks
1 parent cfcf33e commit e32af67

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

JavaScript/Tasks/1-async.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
// Task: rewrite `total` from callbacks contract to async/await
4+
// Hint: do not forget to catch errors with try/catch block
5+
6+
const total = (items, callback) => {
7+
let result = 0;
8+
for (const item of items) {
9+
if (item.price < 0) {
10+
callback(new Error('Negative price is not allowed'));
11+
return;
12+
}
13+
result += item.price;
14+
}
15+
callback(null, result);
16+
};
17+
18+
const electronics = [
19+
{ name: 'Laptop', price: 1500 },
20+
{ name: 'Keyboard', price: 100 },
21+
{ name: 'HDMI cable', price: 10 },
22+
];
23+
24+
total(electronics, (error, money) => {
25+
if (error) console.error({ error });
26+
else console.log({ money });
27+
});

JavaScript/Tasks/2-method.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
// Task: rewrite `total` method from callbacks to async method
4+
5+
class Basket {
6+
#items = null;
7+
8+
constructor(items) {
9+
this.#items = items;
10+
}
11+
12+
total(callback) {
13+
let result = 0;
14+
for (const item of this.#items) {
15+
if (item.price < 0) {
16+
callback(new Error('Negative price is not allowed'));
17+
return;
18+
}
19+
result += item.price;
20+
}
21+
callback(null, result);
22+
}
23+
}
24+
25+
const electronics = [
26+
{ name: 'Laptop', price: 1500 },
27+
{ name: 'Keyboard', price: 100 },
28+
{ name: 'HDMI cable', price: 10 },
29+
];
30+
31+
const basket = new Basket(electronics);
32+
basket.total((error, money) => {
33+
if (error) console.error({ error });
34+
else console.log({ money });
35+
});

0 commit comments

Comments
 (0)