Untitled

mail@pastecode.io avatar
unknown
plain_text
4 years ago
2.2 kB
2
Indexable
Never
class Parking {
    constructor(capacity) {
        this.capacity = Number(capacity);
        this.vehicles = [];
    }

    addCar(carModel, carNumber) {
        if (this.capacity === this.vehicles.length) {
            throw new Error(`Not enough parking space.`);
        }
        this.vehicles.push({
            carModel: carModel,
            carNumber: carNumber,
            payed: false,
        })

        return `The ${carModel}, with a registration number ${carNumber}, parked.`;

    }

    removeCar(carNumber) {
        let test = this.vehicles.find(a => a.carNumber == carNumber);
        if (test == undefined) {
            throw new Error(`The car, you're looking for, is not found.`);
        }
        if (!test.payed) {
            throw new Error(`${carNumber} needs to pay before leaving the parking lot.`);
        }

        this.vehicles = this.vehicles.filter(a => a.carNumber !== carNumber)
        return `${carNumber} left the parking lot.`;
    }

    pay(carNumber) {
        let test = this.vehicles.find(a => a.carNumber === carNumber);
        if (test == undefined) {
            throw new Error(`${carNumber} is not in the parking lot.`);
        }
        if (test.payed) {
            throw new Error(`${carNumber}'s driver has already payed his ticket`);
        }

        test.payed = true;
        return `${carNumber}'s driver successfully payed for his stay.`;
    }

    getStatistics(carNumber) {
        if (carNumber === undefined) {
            let print = [`The Parking Lot has ${this.capacity - this.vehicles.length} empty spots left.`];
            this.vehicles.sort((a, b) => a.carModel.localeCompare(b.carModel)).forEach(element => {
                print.push(`${element.carModel} == ${element.carNumber} - ${element.payed ? 'Has payed' : 'Not payed'}`);
            });
            return print.join('\n');
        }

        let test = this.vehicles.find(a => a.carNumber === carNumber);
        if (test !== undefined) {
            return `${test.carModel} == ${test.carNumber} - ${test.payed ? 'Has payed' : 'Not payed'}`;
        }
    }
}