finalmail

Untitled

Oct 24th, 2020 (edited)
559
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.     addCar(carModel, carNumber) {
  8.         if (this.vehicles.length === this.capacity) {
  9.             throw new Error('Not enough parking space.')
  10.         }
  11.  
  12.         const newVehicle = {
  13.             carModel,
  14.             carNumber,
  15.             payed: false
  16.         }
  17.         this.vehicles.push(newVehicle)
  18.  
  19.         return `The ${carModel}, with a registration number ${carNumber}, parked.`
  20.     }
  21.  
  22.     removeCar(carNumber) {
  23.         const foundCar = this.vehicles.find(veh => veh.carNumber === carNumber)
  24.         if (!foundCar) {
  25.             throw new Error("The car, you're looking for, is not found.")
  26.         }
  27.  
  28.         if (!foundCar.payed) {
  29.             throw new Error(`${carNumber} needs to pay before leaving the parking lot.`)
  30.         }
  31.  
  32.         this.vehicles = this.vehicles.filter(v => v.carNumber !== carNumber)
  33.         return `${carNumber} left the parking lot.`
  34.     }
  35.  
  36.     pay(carNumber) {
  37.         const foundCar = this.vehicles.find(veh => veh.carNumber === carNumber)
  38.         if (!foundCar) {
  39.             throw new Error(`${carNumber} is not in the parking lot.`)
  40.         }
  41.  
  42.         if (foundCar.payed) {
  43.             throw new Error(`${carNumber}'s driver has already payed his ticket.`)
  44.        }
  45.  
  46.        foundCar.payed = true
  47.        return `${carNumber}'s driver successfully payed for his stay.`
  48.     }
  49.  
  50.     // carNumber is optional
  51.     getStatistics(carNumber) {
  52.         if (carNumber === undefined) {
  53.             const emptySlots = this.capacity - this.vehicles.length
  54.             const allVehiclesStats = this.vehicles.map(this.getVehicleStats)
  55.             return [`The Parking Lot has ${emptySlots} empty spots left.`, ...allVehiclesStats].join('\n')
  56.         }
  57.  
  58.         const foundCar = this.vehicles.find(veh => veh.carNumber === carNumber)
  59.         return this.getVehicleStats(foundCar)
  60.     }
  61.  
  62.     getVehicleStats({ carModel, carNumber, payed }) {
  63.         return `${carModel} == ${carNumber} - ${payed ? 'Has payed' : 'Not payed'}`
  64.     }
  65. }
  66.  
  67. const parking = new Parking(12)
  68.  
  69. console.log(parking.addCar('Volvo t600', 'TX3691CA'))
  70. console.log(parking.getStatistics())
  71.  
  72. console.log(parking.pay('TX3691CA'))
  73. console.log(parking.removeCar('TX3691CA'))
  74.  
RAW Paste Data