|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Task: rewrite `total` function to be async with JavaScript timers |
| 4 | +// Use `setInterval` and `clearInterval` to check next item each 1 second |
| 5 | +// Calculations will be executed asynchronously because of timers |
| 6 | +// Run `total` twice (as in example below) but in parallel |
| 7 | +// Print debug output for each calculation step (each second) |
| 8 | +// |
| 9 | +// Hint: example output: |
| 10 | +// { check: { item: { name: 'Laptop', price: 1500 } } } |
| 11 | +// { check: { item: { name: 'Laptop', price: 1500 } } } |
| 12 | +// { check: { item: { name: 'Keyboard', price: 100 } } } |
| 13 | +// { check: { item: { name: 'Keyboard', price: 100 } } } |
| 14 | +// { check: { item: { name: 'HDMI cable', price: 10 } } } |
| 15 | +// { check: { item: { name: 'HDMI cable', price: 10 } } } |
| 16 | +// { money: 1610 } |
| 17 | +// { money: 1610 } |
| 18 | + |
| 19 | +const total = (items, callback) => { |
| 20 | + let result = 0; |
| 21 | + for (const item of items) { |
| 22 | + console.log({ check: { item } }); |
| 23 | + if (item.price < 0) { |
| 24 | + callback(new Error('Negative price is not allowed')); |
| 25 | + return; |
| 26 | + } |
| 27 | + result += item.price; |
| 28 | + } |
| 29 | + callback(null, result); |
| 30 | +}; |
| 31 | + |
| 32 | +const electronics = [ |
| 33 | + { name: 'Laptop', price: 1500 }, |
| 34 | + { name: 'Keyboard', price: 100 }, |
| 35 | + { name: 'HDMI cable', price: 10 }, |
| 36 | +]; |
| 37 | + |
| 38 | +total(electronics, (error, money) => { |
| 39 | + if (error) console.error({ error }); |
| 40 | + else console.log({ money }); |
| 41 | +}); |
| 42 | + |
| 43 | +total(electronics, (error, money) => { |
| 44 | + if (error) console.error({ error }); |
| 45 | + else console.log({ money }); |
| 46 | +}); |
0 commit comments