JSFiddle - React, Tailwind, and code Playground

by Emily Humphrey

JavaScript

class CarSlot {
    constructor(id){
        this.id = id + 1;
        this.empty = true;
        this.carId = false;
    }
    fillSlot(carId){
        this.carId = carId;
        this.empty = false;
				console.log(carId + " sucessfully parked in slot " + this.id);
    }
    emptySlot(carId){
        this.carId = false;
        this.empty = true;
				console.log(carId + " sucessfully left slot " + this.id);
    }
}

class ParkingLot {
    constructor(amountOfSlots){
        this.slots = [];
        for(var i = 0; i < amountOfSlots; i++) {
            this.slots.push(new CarSlot(i))
        } 
    }
    park(carId){
			const openSlot = this.slots.find(x => x.empty);
			if(!openSlot) {
				console.warn(carId + " could not be parked because the lot is full")
				return false;
			}
			openSlot.fillSlot(carId);
			
    }
    getSlots(){
        const slotStatus = this.slots.map(x => x.empty ? `slot ${x.id} is empty` : `Parked at slot ${x.id}: ${x.carId}`);
        return slotStatus;
    }
    remove(carId){
        const usedSlot = this.slots.find(x => x.carId === carId);
				if(!usedSlot) {
					console.warn(carId + " was not found in the lot")
					return false;
				}
				usedSlot.emptySlot(carId);
    }
}

var lotA = new ParkingLot(5);
lotA.park("CAR-1");
lotA.park("CAR-2");
lotA.park("CAR-3");
lotA.park("CAR-4");
lotA.park("CAR-5");
lotA.remove("CAR-1");
lotA.remove("CAR-4");
lotA.remove("CAR-3");
lotA.park("CAR-9");
lotA.park("CAR-10");
console.log(lotA.getSlots())