Advertisement
Liliana797979

3_parking js advanced exam

Oct 12th, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Parking {
  2.     constructor(capacity) {
  3.         this.capacity = capacity;
  4.         this.vehicles = [];
  5.     }
  6.  
  7.  
  8.     addCar(carModel, carNumber) {
  9.         if (this.capacity === this.vehicles.length) {
  10.             throw Error("Not enough parking space.")
  11.         } else {
  12.             this.vehicles.push({ carModel, carNumber, payed: false });
  13.             return `The ${carModel}, with a registration number ${carNumber}, parked.`
  14.         }
  15.     }
  16.  
  17.     removeCar(carNumber) {
  18.         let find = this.vehicles.find((o) => { return o.carNumber === carNumber });
  19.  
  20.         if (!find) {
  21.             throw Error("The car, you're looking for, is not found.")
  22.         }
  23.  
  24.         if (!find.payed) {
  25.             throw Error(`${carNumber} needs to pay before leaving the parking lot.`)
  26.         }
  27.  
  28.         let i = this.vehicles.indexOf(find);
  29.         this.vehicles.splice(i, 1);
  30.  
  31.         return `${carNumber} left the parking lot.`
  32.     }
  33.  
  34.     pay(carNumber) {
  35.         let c = this.vehicles.find((o) => { return o.carNumber === carNumber });
  36.  
  37.         if (!c) {
  38.             throw Error(`${carNumber} is not in the parking lot.`)
  39.         }
  40.  
  41.         if (c.payed) {
  42.             throw Error(`${carNumber}'s driver has already payed his ticket.`);
  43.        }
  44.  
  45.        c.payed = true;
  46.        return `${carNumber}'s driver successfully payed for his stay.`
  47.     }
  48.  
  49.     getStatistics(carNumber) {
  50.         if (!carNumber) {
  51.             let result = [`The Parking Lot has ${this.capacity - this.vehicles.length} empty spots left.`,]
  52.             let sorted = this.vehicles.sort((a, b) => a.carModel.localeCompare(b.carModel));
  53.  
  54.             for (const s of sorted) {
  55.                 if (s.payed) {
  56.                     result.push(`${s.carModel} == ${s.carNumber} - Has payed`)
  57.                 } else {
  58.                     result.push(`${s.carModel} == ${s.carNumber} - Not payed`)
  59.                 }
  60.             }
  61.             return result.join('\n')
  62.         } else {
  63.             let x = this.vehicles.find((o) => { return o.carNumber === carNumber });
  64.  
  65.             if (x.payed) {
  66.                 return `${x.carModel} == ${carNumber} - Has payed`;
  67.             } else {
  68.                 return `${x.carModel} == ${carNumber} - Not payed`;
  69.             }
  70.         }
  71.     }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement