1
+ /*
2
+ * EJERCICIO:
3
+ * Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility
4
+ * Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento
5
+ * de forma correcta e incorrecta.
6
+ */
7
+
8
+ // Correcto
9
+ class User {
10
+ constructor ( name , age , email ) {
11
+ this . name = name
12
+ this . age = age
13
+ this . email = email
14
+ }
15
+ }
16
+
17
+ class SaveUser {
18
+ save ( user ) {
19
+ return
20
+ }
21
+ }
22
+
23
+ class GetUsers {
24
+ getUsers ( ) {
25
+ return
26
+ }
27
+ }
28
+
29
+ // Incorrecto
30
+ class User_2 {
31
+ constructor ( name , age , email ) {
32
+ this . name = name
33
+ this . age = age
34
+ this . email = email
35
+ }
36
+
37
+ save ( user ) {
38
+ return
39
+ }
40
+
41
+ getUsers ( ) {
42
+ return
43
+ }
44
+ }
45
+
46
+ /*
47
+ * DIFICULTAD EXTRA (opcional):
48
+ * Desarrolla un sistema de gestión para una biblioteca. El sistema necesita
49
+ * manejar diferentes aspectos como el registro de libros, la gestión de usuarios
50
+ * y el procesamiento de préstamos de libros.
51
+ * Requisitos:
52
+ * 1. Registrar libros: El sistema debe permitir agregar nuevos libros con
53
+ * información básica como título, autor y número de copias disponibles.
54
+ * 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con
55
+ * información básica como nombre, número de identificación y correo electrónico.
56
+ * 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios
57
+ * tomar prestados y devolver libros.
58
+ * Instrucciones:
59
+ * 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje
60
+ * los tres aspectos mencionados anteriormente (registro de libros, registro de
61
+ * usuarios y procesamiento de préstamos).
62
+ * 2. Refactoriza el código: Separa las responsabilidades en diferentes clases
63
+ * siguiendo el Principio de Responsabilidad Única.
64
+ */
65
+
66
+ class Library {
67
+ constructor ( ) {
68
+ this . books = [ ]
69
+ this . users = [ ]
70
+ this . loans = [ ]
71
+ }
72
+
73
+ booksRegister ( title , author , availableCopies ) {
74
+ if ( availableCopies > 0 ) {
75
+ this . books . push ( { title, author, availableCopies } )
76
+ } else {
77
+ console . log ( 'Cantidad de copias debe ser mayor a 0' )
78
+ }
79
+ }
80
+
81
+ usersRegister ( name , id , email ) {
82
+ this . users . push ( { name, id, email } )
83
+ }
84
+
85
+ booksLoan ( state , quantity , bookTitle , userId ) {
86
+ if ( state === 'prestar' ) {
87
+ let bookFound = false
88
+
89
+ this . books . forEach ( book => {
90
+ if ( book . title === bookTitle ) {
91
+ bookFound = true
92
+ if ( quantity > 0 && book . availableCopies >= quantity ) {
93
+ console . log ( 'Libro prestado' )
94
+ book . availableCopies -= quantity
95
+ this . loans . push ( { bookTitle, userId, quantity } )
96
+ } else {
97
+ console . log ( 'No hay suficientes copias disponibles para prestar' )
98
+ }
99
+ }
100
+ } )
101
+
102
+ if ( ! bookFound ) {
103
+ console . log ( 'Libro no encontrado' )
104
+ }
105
+
106
+ } else if ( state === 'devolver' ) {
107
+ let loanFound = false
108
+
109
+ this . loans = this . loans . filter ( item => {
110
+ if ( item . bookTitle === bookTitle && item . userId === userId ) {
111
+ loanFound = true
112
+ this . books . forEach ( book => {
113
+ if ( book . title === bookTitle ) {
114
+ console . log ( 'Libro devuelto' )
115
+ book . availableCopies += item . quantity
116
+ }
117
+ } )
118
+ return false
119
+ }
120
+ return true
121
+ } )
122
+
123
+ if ( ! loanFound ) {
124
+ console . log ( 'No se encontró un préstamo correspondiente para devolver' )
125
+ }
126
+
127
+ } else {
128
+ console . log ( 'Opción no válida' )
129
+ }
130
+ }
131
+ }
132
+
133
+ const library = new Library ( )
134
+ library . booksRegister ( 'Harry Potter' , 'J.K. Rowling' , 12 )
135
+ library . booksRegister ( 'Harry Potter 2' , 'J.K. Rowling' , 7 )
136
+ library . booksRegister ( 'Harry Potter 3' , 'J.K. Rowling' , 6 )
137
+ library . usersRegister ( 'Victor' , 123 , '[email protected] ' )
138
+ library . usersRegister ( 'Juan' , 124 , '[email protected] ' )
139
+ library . booksLoan ( 'prestar' , 2 , 'Harry Potter' , 123 )
140
+ library . booksLoan ( 'prestar' , 1 , 'Harry Potter' , 124 )
141
+ library . booksLoan ( 'devolver' , 2 , 'Harry Potter' , 123 )
142
+ console . log ( library )
143
+
144
+ // Refactor SRP
145
+
146
+ class LibraryContent {
147
+ constructor ( books = [ ] , users = [ ] , loans = [ ] ) {
148
+ this . books = books
149
+ this . users = users
150
+ this . loans = loans
151
+ }
152
+ }
153
+
154
+ class BooksRegister {
155
+ constructor ( ) {
156
+ this . books = [ ]
157
+ }
158
+
159
+ booksRegister ( title , author , availableCopies ) {
160
+ if ( availableCopies > 0 ) {
161
+ this . books . push ( { title, author, availableCopies } )
162
+ } else {
163
+ console . log ( 'Cantidad de copias debe ser mayor a 0' )
164
+ }
165
+ }
166
+ }
167
+
168
+ class UsersRegister {
169
+ constructor ( ) {
170
+ this . users = [ ]
171
+ }
172
+
173
+ usersRegister ( name , id , email ) {
174
+ this . users . push ( { name, id, email } )
175
+ }
176
+ }
177
+
178
+ class BooksLoans {
179
+ constructor ( library ) {
180
+ this . library = library
181
+ }
182
+
183
+ booksLoan ( state , quantity , bookTitle , userId ) {
184
+ if ( state === 'prestar' ) {
185
+ const book = this . library . books . find ( book => book . title === bookTitle )
186
+ const user = this . library . users . find ( user => user . id === userId )
187
+
188
+ if ( book && user ) {
189
+ if ( quantity > 0 && book . availableCopies >= quantity ) {
190
+ console . log ( 'Libro prestado' )
191
+ book . availableCopies -= quantity
192
+ this . library . loans . push ( { bookTitle, userId, quantity } )
193
+ } else {
194
+ console . log ( 'No hay suficientes copias disponibles para prestar' )
195
+ }
196
+ } else {
197
+ console . log ( book ? 'Usuario no encontrado' : 'Libro no encontrado' )
198
+ }
199
+
200
+ } else if ( state === 'devolver' ) {
201
+ const loanIndex = this . library . loans . findIndex (
202
+ loan => loan . bookTitle === bookTitle && loan . userId === userId
203
+ )
204
+
205
+ if ( loanIndex !== - 1 ) {
206
+ const loan = this . library . loans [ loanIndex ]
207
+ const book = this . library . books . find ( book => book . title === bookTitle )
208
+
209
+ if ( book ) {
210
+ console . log ( 'Libro devuelto' )
211
+ book . availableCopies += loan . quantity
212
+ this . library . loans . splice ( loanIndex , 1 )
213
+ }
214
+ } else {
215
+ console . log ( 'No se encontró un préstamo correspondiente para devolver' )
216
+ }
217
+
218
+ } else {
219
+ console . log ( 'Opción no válida' )
220
+ }
221
+ }
222
+ }
223
+
224
+
225
+ let bookRegister = new BooksRegister ( )
226
+ bookRegister . booksRegister ( 'Harry Potter' , 'J.K. Rowling' , 12 )
227
+ bookRegister . booksRegister ( 'Harry Potter 2' , 'J.K. Rowling' , 22 )
228
+ bookRegister . booksRegister ( 'Harry Potter 3' , 'J.K. Rowling' , 2 )
229
+
230
+ let userRegister = new UsersRegister ( )
231
+ userRegister . usersRegister ( 'Victor' , 1231 , '[email protected] ' )
232
+ userRegister . usersRegister ( 'Juan' , 1232 , '[email protected] ' )
233
+ userRegister . usersRegister ( 'John' , 1233 , '[email protected] ' )
234
+ userRegister . usersRegister ( 'Alfred' , 1234 , '[email protected] ' )
235
+
236
+
237
+ let myLibrary = new LibraryContent ( bookRegister . books , userRegister . users )
238
+
239
+
240
+ let loansSystem = new BooksLoans ( myLibrary )
241
+ loansSystem . booksLoan ( 'prestar' , 2 , 'Harry Potter' , 1231 )
242
+ loansSystem . booksLoan ( 'prestar' , 1 , 'Harry Potter' , 1232 )
243
+ loansSystem . booksLoan ( 'devolver' , 2 , 'Harry Potter' , 1231 )
244
+
245
+ console . log ( myLibrary . books )
246
+ console . log ( myLibrary . users )
247
+ console . log ( myLibrary . loans )
0 commit comments