-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.js
100 lines (95 loc) · 2.16 KB
/
proxy.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// You should use proxy pattern when you want to extend a
// class functionality without changing its implementation
/****************
Original Class
****************/
function Hotel(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize) {
this.stars = stars;
this.isCityCenter = isCityCenter;
this.isNew = isNew;
this.numberOfRooms = numberOfRooms;
this.avgRoomSize = avgRoomSize;
}
Hotel.prototype = { // Define getters and setters
getStars: function() {
return this.stars;
},
setStars: function(starsRate) {
this.stars = starsRate;
},
isCityCenter: function() {
return this.isCityCenter;
},
toggleCenter: function() {
this.isCityCenter = !this.isCityCenter;
},
isNew: function() {
return this.isNew;
},
toggleNew: function() {
this.isNew = !this.isNew;
},
getNumberOfRooms: function() {
return this.numberOfRooms;
},
setNumberOfRooms: function(num) {
this.numberOfRooms = num;
},
getAvgRoomSize: function() {
return this.avgRoomSize;
},
setAvgRoomSize: function(newAvg) {
this.avgRoomSize = newAvg;
}
}
/****************
Proxy
****************/
var HotelProxy = function(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize) {
// Create Hotel Instance
var hotel = new Hotel(stars, isCityCenter, isNew, numberOfRooms, avgRoomSize);
// Private function
function scoreByStars(stars) {
switch(stars) {
case(5):
return 6;
case(4):
return 5;
case(3):
return 3;
case(2):
return 1.5;
default:
return 0.5;
}
}
// Extend hotel instance
Object.assign(hotel, {
getScore: function() {
var score = scoreByStars(hotel.stars);
if(hotel.isCityCenter) {
score += 2;
}
if(hotel.isNew) {
score += 1.5;
}
if(hotel.numberOfRooms > 5000) {
score += 0.5;
}
return score;
},
getHotelRoomsVolume: function() {
return hotel.numberOfRooms * hotel.avgRoomSize;
}
});
// Return extended instance
return hotel;
}
// Usage example
var hp = HotelProxy(4, true, false, 2800, 150);
console.log(hp.getScore()); // 7
console.log(hp.getHotelRoomsVolume()); // 420000
hp.setAvgRoomSize(160);
console.log(hp.getHotelRoomsVolume()); // 448000
hp.setStars(5);
console.log(hp.getScore()); //8