Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function needForSpeed(arr) {
- class Car {
- constructor(model, mileage, fuel) {
- this.model = model;
- this.mileage = mileage;
- this.fuel = fuel;
- }
- drive(params) {
- let [distance, fuelNeeded] = params;
- if (this.fuel < fuelNeeded) {
- console.log('Not enough fuel to make that ride');
- return;
- }
- this.mileage += distance;
- this.fuel -= fuelNeeded;
- console.log(
- `${this.model} driven for ${distance} kilometers. ${fuelNeeded} liters of fuel consumed.`
- );
- }
- refuel(params) {
- let [fuelRefill] = params;
- let oldFuel = this.fuel;
- this.fuel =
- this.fuel + fuelRefill >= MAX_FUEL ? MAX_FUEL : this.fuel + fuelRefill;
- console.log(`${this.model} refueled with ${this.fuel - oldFuel} liters`);
- }
- revert(params) {
- let [kilometers] = params;
- this.mileage -= kilometers;
- if (this.mileage < MIN_MILEAGE) {
- this.mileage = MIN_MILEAGE;
- return;
- }
- console.log(
- `${this.model} mileage decreased by ${kilometers} kilometers`
- );
- }
- }
- const carCollection = {};
- const MAX_MILEAGE = 100000;
- const MAX_FUEL = 75;
- const MIN_MILEAGE = 10000;
- let carsNumber = Number(arr[0]);
- //Get cars
- const carData = getCars(carsNumber);
- //Split car data
- carData.forEach((line) => {
- let [car, mileage, fuel] = line.split('|');
- mileage = Number(mileage);
- fuel = Number(fuel);
- //Add cars to collection
- carCollection[car] = new Car(car, mileage, fuel);
- });
- //Get commands
- let index = carsNumber + 1;
- while (arr[index] !== 'Stop') {
- let [command, model, ...args] = arr[index].split(' : ');
- command = command.toLowerCase();
- args = args.map(Number);
- //Execute command
- carCollection[model][command](args);
- //Remove old cars from collection
- if (carCollection[model].mileage >= MAX_MILEAGE) {
- console.log(`Time to sell the ${model}!`);
- delete carCollection[model];
- }
- index++;
- }
- //Output
- const output = [];
- Object.keys(carCollection)
- .sort((a, b) => a.localeCompare(b))
- .sort((a, b) => {
- return carCollection[b].mileage - carCollection[a].mileage;
- })
- .forEach((car) => {
- let msg = `${car} -> Mileage: ${carCollection[car].mileage} kms, Fuel in the tank: ${carCollection[car].fuel} lt.`;
- output.push(msg);
- });
- console.log(output.join('\n'));
- //Declarations
- function getCars(num) {
- const cars = [];
- for (let i = 1, l = num + 1; i < l; i++) {
- cars.push(arr[i]);
- }
- return cars;
- }
- }
- let result = needForSpeed([
- '4',
- 'Lamborghini Veneno|11111|74',
- 'Bugatti Veyron|12345|67',
- 'Koenigsegg CCXR|67890|12',
- 'Aston Martin Valkryie|99900|50',
- 'Drive : Koenigsegg CCXR : 382 : 82',
- 'Drive : Aston Martin Valkryie : 99 : 23',
- 'Drive : Aston Martin Valkryie : 2 : 1',
- 'Refuel : Lamborghini Veneno : 40',
- 'Revert : Bugatti Veyron : 2000',
- 'Stop',
- ]);
- console.log(result);
Add Comment
Please, Sign In to add comment