Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

How to Solve the Parking Lot Challenge in JavaScript

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;
Comment

PREVIOUS NEXT
Code Example
Javascript :: jQuery Misc Methods 
Javascript :: add text to each element in an array javascript 
Javascript :: Looping through array, fetching tweets and returning new reversed array javascript react 
Javascript :: send a message in the first channel discord.js 
Javascript :: react mui pagination change text color site:stackoverflow.com 
Javascript :: errors thrown inside asynchronous functions will act like uncaught errors 
Javascript :: check token balance of an address using web3 
Javascript :: Backbone View Template 
Javascript :: js filter out html 
Javascript :: simple express server responce html css js 
Javascript :: how to create existing nodes in godot 
Javascript :: Backbone With Express 
Javascript :: jquery issue stack 
Javascript :: react private routes 
Javascript :: Backbone View In Another View 
Javascript :: remove parent element jquery 
Javascript :: how to print reverse number in javascript 
Javascript :: javascript add button 
Javascript :: javascript every function 
Javascript :: find an element 
Javascript :: js replace last occurrence of string 
Javascript :: events node.js 
Javascript :: Pause the stream returned by getUserMedia 
Javascript :: assing multipe ids jquery to event 
Javascript :: jquery ui sortable between two tables 
Javascript :: JavaScript Precision Problems 
Javascript :: intervals 
Javascript :: react linkify 
Javascript :: javascript addall 
Javascript :: roman to integer fastest way 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =