Liliana797979

class storage1 - fundamentals

Jul 20th, 2021
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.      
  2.     class Storage {
  3.         constructor(capacity) {
  4.             this.capacity = capacity;
  5.             this.storage = [];
  6.         }
  7.  
  8.         get totalCost() {
  9.             // reduce(function (accumulator, currentValue) {return accumulator + currentValue.x}, initialValue)
  10.             // If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0. If the array is empty and NO initialValue is provided, TypeError will be thrown.
  11.             return this.storage.reduce((acc, el) => {
  12.                 return acc + el.price * el.quantity;
  13.             }, 0);
  14.         }
  15.  
  16.         addProduct(product) {
  17.             this.storage.push(product);
  18.             this.capacity -= product.quantity;
  19.             return;
  20.         }
  21.  
  22.         getProducts() {
  23.             let output = [];
  24.             this.storage.forEach(product => {
  25.                 output.push(JSON.stringify(product));
  26.             });
  27.             return output.join('\n');
  28.         }
  29.     }
Advertisement
Add Comment
Please, Sign In to add comment