darkmavis1980

Untitled

Oct 24th, 2021 (edited)
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const orders = [
  2.   {
  3.     id: 123,
  4.     name: 'Alex',
  5.     age: 32,
  6.     cart: [
  7.       {
  8.         productId: 234,
  9.         price: 23.99,
  10.         quantity: 3,
  11.       },
  12.       {
  13.         productId: 235,
  14.         price: 39.99,
  15.         quantity: 4,
  16.       },
  17.     ],
  18.   },
  19.   {
  20.     id: 124,
  21.     name: 'Steve',
  22.     age: 22,
  23.     cart: [
  24.       {
  25.         productId: 234,
  26.         price: 23.99,
  27.         quantity: 1,
  28.       },
  29.     ],
  30.   },{
  31.     id: 125,
  32.     name: 'Joe',
  33.     age: 43,
  34.   },
  35. ];
  36.  
  37. const findCustomer = customerName => {
  38.   const customer = orders.find(order => order.name === customerName);
  39.   if (!customer) throw new Error('Customer not found');
  40.   return customer;
  41. }
  42.  
  43. const totalOrderValue = (customerName) => {
  44.   try {
  45.     const customer = findCustomer(customerName);
  46.  
  47.     if (!customer.cart) {
  48.       return 0;
  49.     }
  50.  
  51.     const reducer = (sum, {quantity, price}) => sum += quantity * price;
  52.     return customer.cart.reduce(reducer, 0);
  53.   } catch (error) {
  54.     console.log(error.message);
  55.   }
  56. }
  57.  
  58. console.log(totalOrderValue('Alex')); // 231.93
  59. console.log(totalOrderValue('Steve')); // 23.99
  60. console.log(totalOrderValue('Joe')); // 0
  61. console.log(totalOrderValue('Wally')); // show an error
  62.  
  63. const invoiceForCustomer = (customerName) => {
  64.   try {
  65.     const customer = findCustomer(customerName);
  66.  
  67.     if (!customer.cart) {
  68.       return [];
  69.     }
  70.  
  71.     return customer.cart.map(({quantity, price}) => quantity * price);
  72.   } catch (error) {
  73.     console.log(error.message);
  74.   }
  75. }
  76.  
  77. console.log(invoiceForCustomer('Alex')); // [ 71.97, 159.96 ]
  78. console.log(invoiceForCustomer('Steve')); // [ 23.99 ]
  79. console.log(invoiceForCustomer('Joe')); // []
  80. console.log(invoiceForCustomer('Wally')); // show an error
Add Comment
Please, Sign In to add comment