mihail gaberov

Learning by sharing.

How to Solve the Parking Lot Challenge in JavaScript

Last updated: Jul 11, 2022

With interactive demo

Have you heard about the Parking Lot?

Yes?

No?

Ok, let me explain briefly.

The Parking Lot is challenge where you are asked to write a class that manage an imaginary parking lot. In this tutorial we will do that in JavaScript. And to make it a bit more interesting, we will create a small React app that will visualize the workings of our class.

Let's begin 🎉

Challenge Requirements

You have to implement a class in JavaScript. That class should consist of variables and methods enough to simulate the work of a parking lot. Here are the details:

  • We should be able to create the parking with give size (number of parking spots)
  • We don’t do any differentiation among different vehicles, i.e. we consider them all the same
  • Our class provides a method for parking new cars in the parking
  • Our class provides a method for removing already parked cars and
  • Our class provides a method for getting the size of the parking (total count of slots)
  • Solution

    Let’s take a look first at the class logic itself.

    It’s pretty straightforward and I am sure there won’t be any surprises for most of you. Especially if you already have some programming experience. Especially in OOP and class based languages.

    class ParkingLot

    I will give you the code first and then will follow up with short explanation on the implementation.

    class ParkingLot {
      slots = [];
    
      constructor(parkingSize) {
        this.slots = new Array(parkingSize).fill(null);
      }
    
      park(carId) {
        console.log(`Parking car: ${carId}`);
        if (this.slots.every((slot) => slot !== null)) {
          return false;
        }
    
        for (let i = 0; i <= this.slots.length; i++) {
          const slot = this.slots[i];
    
          if (slot === null) {
            this.slots[i] = carId;
            return true;
          }
        }
      }
    
      remove(carId) {
        console.log(`Leaving car: ${carId}`);
        if (this.slots.every((slot) => slot !== carId)) {
          return false;
        }
    
        for (let i = 0; i <= this.slots.length; i++) {
          const slot = this.slots[i];
    
          if (slot === carId) {
            this.slots[i] = null;
            return true;
          }
        }
      }
    
      getSlots() {
        console.log(`Parking slots: ${this.slots}`);
        return this.slots;
      }
    
      getSize() {
        console.log(`Parking size is: ${this.slots.length}`);
        return this.slots.length;
      }
    
      getAvailable() {
        const availableSlots = this.slots.filter((s) => s === null).length;
        console.log(`Available parking slots: ${availableSlots}`);
        return availableSlots;
      }
    
      isFull() {
        return this.getAvailable() === 0;
      }
    }
    
    export default ParkingLot;

    Starting from the beginning - our class has one property, slots which is going to be an array storing info about the parking slots - free and occupied.

    Then we have a constructor method, this is the method that gets executed every time you create an instance of this class. Here is where we use an input number parameter, called parkingSize, to create an empty array with length equal to that number. Technically speaking, this array is not empty, as we initialize it with null values. This means that after execution of the code in the constructor, we will end up with an array filled with null values, depending on the number we passed in. For example, if we execute this:

    const parking = new ParkingLot(5);

    It will result in this:

    [null, null, null, null, null] // lenght = 5
    
    instead of [] // empty array, length 0

    After going through the constructor, let’s take a look at the rest of the methods in the class.

    park() - This is where we do the actual parking of a car. This method is iterating over the slots array, checks if there are free spots, i.e. slots that are still equal to null, and add in there the car. Cars are given by carId. This is just an identifier we use to signify we have a car in a certain spot. Make a note that this method returns false in case there are not free slots, or true if parking was successful.

    getSlots() - Helper method, it just returns the array we use to store the parking slots.

    remove() - This is how we remove cars from the parking lot. This method also iterates over the slots array.

    💡As you may have noticed till now, in almost every case when we need to manipulate data, stored in a data structure like array, we would have to iterate over this structure so that we can access its elements. Different programming languages provide different data structures and methods to work with them, but the main idea is always the same - when you need to do something with this data, you need to iterate over it in some way.

    To remove a car from the parking, we use the afore mentioned identifier. We look for such item in the slots array and if we got a match, we have a car to ‘un-park’. We perform the actual removal by just setting that specific slot to null again.

    Now you can guess why we decided to initialize our slots array with nulls in the first place.

    This method also returns boolean result depending on whether there was a successful removal or not. We should be able to use this feedback when building some kind of UI that would be able to react on such changes. Same is valid for when adding cars to the parking (look at park method).

    getSize() - Another helper method, we use to check the parking size.

    getAvailable() - This one shows us how many available slot we currently have.

    isFull() - Tells us if the parking is full, i.e. no more available slots.

    React app

    Parking Lot app - main screen
    Parking Lot app - main screen

    Here is where the fun starts. 🕺

    We are going to create an interactive app, visualizing the tasks which we could perform with the help of our implementation above.

    Our app will provide basic UI controls allowing an (imaginary) operator to work with the parking lot software. And in order to make his working life a bit more eye-pleasing, we will try to animate the basic functions our software provides.

    Let’s see how! 📺

    Demo

    Here is the live demo for those of you who doesn’t care about the details and just want to ‘taste’ it 🥪

    Parking Lot Inc. app

    Source Code

    Here is the repo with the app source code.

    Let me give you a brief summary on the what and the why.

    The app is built with vite. The reason for this is that I have been playing recently with it and I am really happy with the speed and the performance it provides. No matter it’s still in relatively early stages of developing, if I am about to start a new project and am in a position to choose, I will go with vite. This is not to say I have anything against its big brother CRA. Just on contrary - I have built multiple apps with it and I am still using it in some of my projects. It’s just that vite is much faster and it’s giving me everything I currently need.

    💡Everybody must keep in mind that selecting given technology is always depends on the specific needs in the specific project. That is to say that there is no silver bullet. It’s always a matter of requirements and priorities.

    Structure

    App structure
    App structure

    The app structure is straightforward. On root level we have two folders - assets and src. The first contains the assets used in the app, in this case it’s just a car image. The later contains all the files with the source code.

    Let’s take a closer look inside the source folder.

    Here we have the following folders:

  • components - contains all React components used in the app
  • lib - contains the parking lot class, responsible for the main logic of the app
  • pages - contains two sub-directories, respectively for the two main screens in the app - Landing and Main
  • utils - contains a helper method for generating fictitious car number plates, that are used later when representing a parking slot as busy
  • And several files, most of them are related to the entry point of the app, except the favicon ones - their role should be obvious for you. If not - take a look at the tab of your browser 😉

    Browser tab with favicon
    Browser tab with favicon

    Pages

    As mentioned earlier, the main pages (also called screens) in the app are called Landing and Main. These are React components themselves. They serve as skeletons for everything you see in the welcome page - where you land initially and where you can select how many parking slots you want to have in your parking lot.

    Welcome page
    Welcome page

    And the page you go after clicking the big, pink submit button - the main screen where your operator is able to manage the parking lot.

    Main page
    Main page

    Functionality

    The app provides very basic functionality for managing an imaginary parking lot. When the user select how many slots he wants (max 20), he will be transitioned to the main screen. There he will be able to see all free parking slots. When a car is parked, via the PARK! button, the relevant spot will be visualised as busy and will show the registration number of the car being parked there. The operator could un-park cars by clicking on a busy slot, i.e. on the car he wants to “remove” from the parking lot.

    💡The simple animation of the moving red car is just for visual delights and doesn’t have any real influence on the way the parking works.

    I used CSS modules for styling the app. I also tried to make the app a bit mobile friendly, in case you decide to try it on your mobile device.

    Be my guest and give a try 🧪 

    Conclusion

    My initial idea behind this post was to describe the parking lot class itself. You know, just for educational purposes. To show you how can you write such a class in JavaScript.

    But then I thought it’s kind of boring 🥱.  I wanted to create something funnier 💃🏻, something more gamified 🕹️  sort to say.

    And this is how I ended up with this mini game-like app 🎮.

    While building it, my 5 years old daughter 🧒🏻 saw it and wanted to play with it. And she had a lot of fun actually!

    Yes, yes, of course! I am not saying that if it was something funny for a 5y old, it will be for you too 😀.

    My only goal was to catch your attention through the game, so that the knowledge 📖 behind it stays longer with you.

    Thanks for reading! 🙏

    ← Go home