Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CarDealership {
- constructor(name) {
- this.name = name;
- this.availableCars = [];
- this.soldCars = [];
- this.totalIncome = 0;
- }
- addCar(model, horsepower, price, mileage) {
- if (
- model == '' ||
- horsepower < 0 ||
- !Number.isInteger(horsepower) ||
- price < 0 ||
- mileage < 0
- ) {
- throw new Error('Invalid input!');
- }
- this.availableCars.push({ model, horsepower, price, mileage });
- return `New car added: ${model} - ${horsepower} HP - ${mileage.toFixed(
- 2
- )} km - ${price.toFixed(2)}$`;
- }
- sellCar(model, desiredMileage) {
- let searchedCar = this.availableCars.find((o) => o.model == model);
- if (!searchedCar) {
- throw new Error(`${model} was not found!`);
- }
- if (searchedCar.mileage - desiredMileage > 40000) {
- searchedCar.price *= 0.9;
- } else if (
- searchedCar.mileage - desiredMileage <= 40000 &&
- searchedCar.mileage - desiredMileage > 0
- ) {
- searchedCar.price *= 0.95;
- }
- let soldCarIndex = this.availableCars.findIndex(
- (o) => o == searchedCar
- );
- this.availableCars.splice(soldCarIndex, 1);
- this.soldCars.push({
- model: searchedCar.model,
- horsepower: searchedCar.horsepower,
- soldPrice: searchedCar.price,
- });
- this.totalIncome += searchedCar.price;
- return `${model} was sold for ${searchedCar.price.toFixed(2)}$`;
- }
- currentCar() {
- if (this.availableCars.length == 0) {
- return 'There are no available cars';
- }
- let result = [];
- result.push('-Available cars:');
- this.availableCars.forEach((o) =>
- result.push(
- `---${o.model} - ${o.horsepower} HP - ${o.mileage.toFixed(
- 2
- )} km - ${o.price.toFixed(2)}$`
- )
- );
- return result.join('\n');
- }
- salesReport(criteria) {
- let sorted;
- let availableCriteria = ['horsepower', 'model'];
- if (!availableCriteria.includes(criteria)) {
- throw new Error('Invalid criteria!');
- }
- if (criteria == 'model') {
- sorted = this.soldCars.sort((a, b) =>
- a.model.localeCompare(b.model)
- );
- } else {
- sorted = this.soldCars.sort((a, b) => b.horsepower - a.horsepower);
- }
- let result2 = [];
- result2.push(
- `-${this.name} has a total income of ${this.totalIncome.toFixed(
- 2
- )}$`
- );
- result2.push(`-${sorted.length} cars sold:`);
- sorted.forEach((o) =>
- result2.push(
- `---${o.model} - ${o.horsepower} HP - ${o.soldPrice.toFixed(
- 2
- )}$`
- )
- );
- return result2.join('\n');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement