Member-only story
Simulate a Parking Lot application in javascript
Let’s say we have a small parking lot that can only take 5 cars at a time but at the same time there are 10 cars trying to park. Of course, with limited capacity we cannot park all the cars at once so these cars have to wait.
Let’s implement this in javascript where we take in 5 cars simulatenously but the remaining cars will wait until any of these cars left.
Let’s take a look at the following code:
When we park cars, we have 10 cars that want to leave at different pace of times, as seen in the times array. For each car, we attempt to park. If there are spaces, we add in the car otherwise the car would have to be added into the queue.
When the car finished parking, the car can be removed from parking. If there are cars in the queue, then the next car can park. If there are no more cars left, then we can increase one available spot to park.