-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy path4-hell.js
More file actions
62 lines (51 loc) · 1.29 KB
/
4-hell.js
File metadata and controls
62 lines (51 loc) · 1.29 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
'use strict';
// Task: refactor callback hell code with named callbacks
// Restriction: you can change code only in "Usage" section
const getPurchase = (callback) => callback({
Electronics: [
{ name: 'Laptop', price: 1500 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
],
Textile: [
{ name: 'Bag', price: 50 },
],
});
const iterateGroups = (order, callback) => {
for (const groupName in order) {
const group = order[groupName];
callback(group);
}
};
const groupTotal = (items, callback) => {
let total = 0;
for (const item of items) {
total += item.price;
}
callback(total);
};
const budget = (limit) => {
let balance = limit;
const withdraw = (value, callback) => {
const success = balance >= value;
if (success) balance -= value;
callback(success);
};
const rest = (callback) => callback(balance);
return { withdraw, rest };
};
// Usage
const wallet = budget(1650);
getPurchase((purchase) => {
let amount = 0;
iterateGroups(purchase, (group) => {
groupTotal(group, (subtotal) => {
wallet.withdraw(subtotal, (success) => {
if (success) amount += subtotal;
wallet.rest((balance) => {
console.log({ success, amount, subtotal, balance });
});
});
});
});
});