DimiPetrov

parking/js advanced exam

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