Advertisement
Guest User

Untitled

a guest
Oct 18th, 2023
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class CarDealership {
  2.     constructor(name) {
  3.         this.name = name
  4.         this.availableCars = []
  5.         this.soldCars = []
  6.         this.totalIncome = 0
  7.     }
  8.     addCar(model, horsePower, price, mileage) {
  9.         if (model == '' || horsePower < 0 || price < 0 || mileage < 0) {  //point 1
  10.             throw new Error('Invalid input!')
  11.         }
  12.         this.availableCars.push({ model, horsePower, price, mileage })
  13.         return `New car added: ${model} - ${horsePower} HP - ${mileage.toFixed(2)} km - ${price.toFixed(2)}$`
  14.     }
  15.     sellCar(model, desiredMileage) {
  16.         let curr = this.availableCars.find(x => x.model === model)
  17.         if (!curr) {
  18.             throw new Error(`${model} was not found!`)
  19.         } else {
  20.             if (curr.mileage <= desiredMileage) curr.price = curr.price
  21.             else if ((curr.mileage - desiredMileage) <= 40000) curr.price *= 0.95   //point 2
  22.             else curr.price *= 0.90                 //point 2
  23.             this.totalIncome += curr.price
  24.         }
  25.         this.availableCars = this.availableCars.filter(x => x !== curr)
  26.         this.soldCars.push(curr)
  27.         return `${model} was sold for ${curr.price.toFixed(2)}$`
  28.     }
  29.     currentCar() {
  30.         if (this.availableCars.length === 0) {
  31.             return `There are no available cars`
  32.         } else {
  33.             let result = []
  34.             result.push(`-Available cars:`)     //point 3
  35.             this.availableCars.map(x => {
  36.                 result.push(`---${x.model} - ${x.horsePower} HP - ${x.mileage.toFixed(2)} km - ${x.price.toFixed(2)}$`)     //point 3
  37.             })
  38.             return result.join('\n')    //point 3
  39.         }
  40.     }
  41.     salesReport(criteria) {
  42.         if (criteria != 'horsepower' && criteria != 'model') {      //point 4
  43.             throw new Error('Invalid criteria!')
  44.         }
  45.         if (criteria === 'horsepower') {
  46.             this.soldCars.sort((a, b) => b.horsePower - a.horsePower)
  47.         }
  48.         if (criteria === 'model') {
  49.             this.soldCars.sort((a, b) => a.model.localeCompare(b.model))
  50.         }
  51.         let result = []
  52.         this.soldCars.forEach(x => {
  53.             result.push(`---${x.model} - ${x.horsePower} HP - ${(x.price).toFixed(2)}$`);               //point 5
  54.         })
  55.         return `-${this.name} has a total income of ${this.totalIncome.toFixed(2)}$\n-${this.soldCars.length} cars sold:\n${result.join('\n')}`     //point 6
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement