@@ -241,6 +241,16 @@ Denon AH-C720 In-Ear Headphones | 236
241241 ``` js
242242 import * as cheerio from ' cheerio' ;
243243
244+ function parseUnitsText (text ) {
245+ const count = text
246+ .replace (" In stock," , " " )
247+ .replace (" Only" , " " )
248+ .replace (" left" , " " )
249+ .replace (" units" , " " )
250+ .trim ();
251+ return count === " Sold out" ? 0 : parseInt (count);
252+ }
253+
244254 const url = " https://warehouse-theme-metal.myshopify.com/collections/sales" ;
245255 const response = await fetch (url);
246256
@@ -254,16 +264,8 @@ Denon AH-C720 In-Ear Headphones | 236
254264 const title = productItem .find (" .product-item__title" );
255265 const titleText = title .text ().trim ();
256266
257- const unitsText = productItem
258- .find (" .product-item__inventory" )
259- .text ()
260- .replace (" In stock," , " " )
261- .replace (" Only" , " " )
262- .replace (" left" , " " )
263- .replace (" units" , " " )
264- .trim ();
265- const unitsCount = unitsText === " Sold out" ? 0
266- : parseInt (unitsText);
267+ const unitsText = productItem .find (" .product-item__inventory" ).text ();
268+ const unitsCount = parseUnitsText (unitsText);
267269
268270 console .log (` ${ titleText} | ${ unitsCount} ` );
269271 });
@@ -290,6 +292,14 @@ Simplify the code from previous exercise. Use [regular expressions](https://deve
290292 ``` js
291293 import * as cheerio from ' cheerio' ;
292294
295+ function parseUnitsText (text ) {
296+ const match = text .match (/ \d + / );
297+ if (match) {
298+ return parseInt (match[0 ]);
299+ }
300+ return 0 ;
301+ }
302+
293303 const url = " https://warehouse-theme-metal.myshopify.com/collections/sales" ;
294304 const response = await fetch (url);
295305
@@ -303,12 +313,8 @@ Simplify the code from previous exercise. Use [regular expressions](https://deve
303313 const title = productItem .find (" .product-item__title" );
304314 const titleText = title .text ().trim ();
305315
306- const unitsText = productItem
307- .find (" .product-item__inventory" )
308- .text ()
309- .trim ();
310- const unitsCount = unitsText === " Sold out" ? 0
311- : parseInt (unitsText .match (/ \d + / ));
316+ const unitsText = productItem .find (" .product-item__inventory" ).text ();
317+ const unitsCount = parseUnitsText (unitsText);
312318
313319 console .log (` ${ titleText} | ${ unitsCount} ` );
314320 });
0 commit comments