File tree Expand file tree Collapse file tree 4 files changed +46
-19
lines changed Expand file tree Collapse file tree 4 files changed +46
-19
lines changed Original file line number Diff line number Diff line change 11'use strict' ;
22
3- // Task: change `iterate` contract from chainable callbacks
4- // to Promise (chainable or you can call it with await syntax)
3+ // Task: rewrite `total` from callbacks contract to promises
54
6- const iterate = ( items ) => {
7- let index = 0 ;
8- const chain = {
9- next : ( callback ) => {
10- if ( index < items . length ) {
11- callback ( items [ index ++ ] ) ;
12- }
13- return chain ;
5+ const total = ( items , callback ) => {
6+ let result = 0 ;
7+ for ( const item of items ) {
8+ if ( item . price < 0 ) {
9+ callback ( new Error ( 'Negative price is not allowed' ) ) ;
10+ return ;
1411 }
15- } ;
16- return chain ;
12+ result += item . price ;
13+ }
14+ callback ( null , result ) ;
1715} ;
1816
1917const electronics = [
@@ -22,11 +20,7 @@ const electronics = [
2220 { name : 'HDMI cable' , price : 10 } ,
2321] ;
2422
25- // Use await syntax to get items
26- iterate ( electronics ) . next ( ( item ) => {
27- console . log ( item ) ;
28- } ) . next ( ( item ) => {
29- console . log ( item ) ;
30- } ) . next ( ( item ) => {
31- console . log ( item ) ;
23+ total ( electronics , ( error , money ) => {
24+ if ( error ) console . error ( { error } ) ;
25+ else console . log ( { money } ) ;
3226} ) ;
File renamed without changes.
Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ // Task: change `iterate` contract from chainable callbacks
4+ // to Promise (chainable or you can call it with await syntax)
5+
6+ const iterate = ( items ) => {
7+ let index = 0 ;
8+ const chain = {
9+ next : ( callback ) => {
10+ if ( index < items . length ) {
11+ callback ( items [ index ++ ] ) ;
12+ }
13+ return chain ;
14+ }
15+ } ;
16+ return chain ;
17+ } ;
18+
19+ const electronics = [
20+ { name : 'Laptop' , price : 1500 } ,
21+ { name : 'Keyboard' , price : 100 } ,
22+ { name : 'HDMI cable' , price : 10 } ,
23+ ] ;
24+
25+ // Use await syntax to get items
26+ iterate ( electronics ) . next ( ( item ) => {
27+ console . log ( item ) ;
28+ } ) . next ( ( item ) => {
29+ console . log ( item ) ;
30+ } ) . next ( ( item ) => {
31+ console . log ( item ) ;
32+ } ) ;
Original file line number Diff line number Diff line change 33// Task: support rejection with an error, if no more items in
44// `items` array are available to return with `.next()`
55// Change throwing error to returning rejected Promise.
6+ // Catch error with `.catch` or `try/catch` to handle it.
67
78const iterate = ( items ) => {
89 let index = 0 ;
You can’t perform that action at this time.
0 commit comments