-
Notifications
You must be signed in to change notification settings - Fork 70
/
main.js
64 lines (56 loc) · 1.45 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const Stack = require('./Stack');
class Parking {
constructor() {
this.laneX = new Stack(4)
this.laneY = new Stack(4)
this.street = new Stack(3);
this.carsInX = {
// 123: true
}
this.carsInY = {}
}
park(car) {
if (this.laneX.hasSpace()) {
this.laneX.push(car);
this.carsInX[car] = true;
} else if (this.laneY.hasSpace()) {
this.laneY.push(car);
this.carsInY[car] = true;
} else {
throw new Error('Parking full!');
}
}
depart(carId) {
let numOfMoves = 0;
if (carId in this.carsInX) { // in operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
while (this.laneX.peek() !== carId) {
if (this.laneY.hasSpace()) {
let removedCar = this.laneX.pop();
this.laneY.push(removedCar)
} else {
let removedCar = this.laneX.pop();
this.street.push(removedCar)
}
numOfMoves++;
}
let ourCar = this.laneX.pop();
console.log('the car is:', ourCar)
while (!this.street.isEmpty()) {
this.park(this.street.pop())
}
return numOfMoves;
}
}
}
let nycParking = new Parking();
nycParking.park(333)
nycParking.park(123)
nycParking.park(1)
nycParking.park(3)
nycParking.park(5)
nycParking.park(79)
nycParking.park(69)
nycParking.park(100);
// console.log(nycParking.carsInX)
// console.log(nycParking.carsInY)
console.log(nycParking.depart(333))