Skip to content

Commit 97eb70d

Browse files
authored
Merge pull request mouredev#6907 from victor-Casta/[email protected]
#26 - JavaScript
2 parents 8234c4d + b28a778 commit 97eb70d

File tree

2 files changed

+348
-0
lines changed

2 files changed

+348
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* EJERCICIO:
3+
* Explora el concepto de clase y crea un ejemplo que implemente un inicializador,
4+
* atributos y una función que los imprima (teniendo en cuenta las posibilidades
5+
* de tu lenguaje).
6+
* Una vez implementada, créala, establece sus parámetros, modifícalos e imprímelos
7+
* utilizando su función.
8+
*/
9+
10+
class User {
11+
name: string
12+
age: number
13+
email: string
14+
constructor(name: string, age: number, email: string) {
15+
this.name = name
16+
this.age = age
17+
this.email = email
18+
}
19+
20+
print():void {
21+
console.log(`Nombre: ${this.name}, Edad: ${this.age}, Email: ${this.email}`)
22+
}
23+
}
24+
25+
const user1 = new User('Victor', 21, '[email protected]')
26+
user1.print()
27+
28+
/*
29+
* DIFICULTAD EXTRA (opcional):
30+
* Implementa dos clases que representen las estructuras de Pila y Cola (estudiadas
31+
* en el ejercicio número 7 de la ruta de estudio)
32+
* - Deben poder inicializarse y disponer de operaciones para añadir, eliminar,
33+
* retornar el número de elementos e imprimir todo su contenido.
34+
*/
35+
36+
// Pilas - LIFO
37+
38+
class Stack<T> {
39+
private listStack: T[]
40+
41+
constructor() {
42+
this.listStack = []
43+
}
44+
45+
adding(input: T): void {
46+
this.listStack.push(input)
47+
}
48+
49+
removing(): T | undefined {
50+
return this.listStack.pop()
51+
}
52+
53+
numberOfElements(): number {
54+
return this.listStack.length
55+
}
56+
57+
printStackContent(): void {
58+
console.table(this.listStack)
59+
}
60+
}
61+
62+
const numberStack = new Stack<number>()
63+
numberStack.adding(1)
64+
numberStack.adding(2)
65+
numberStack.adding(3)
66+
numberStack.removing()
67+
console.log(numberStack.numberOfElements())
68+
numberStack.printStackContent()
69+
70+
// Colas - FIFO
71+
72+
class Queue<T> {
73+
private listQueue: T[]
74+
75+
constructor() {
76+
this.listQueue = []
77+
}
78+
adding(input: T): void {
79+
this.listQueue.push(input)
80+
}
81+
82+
removing(): T | undefined {
83+
return this.listQueue.shift()
84+
}
85+
86+
numberOfElements(): number {
87+
return this.listQueue.length
88+
}
89+
90+
printStackContent(): void {
91+
console.table(this.listQueue)
92+
}
93+
}
94+
95+
const myQueue: Queue<number> = new Queue()
96+
myQueue.adding(1)
97+
myQueue.adding(2)
98+
myQueue.adding(3)
99+
myQueue.removing()
100+
console.log(myQueue.numberOfElements())
101+
myQueue.printStackContent()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
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

Comments
 (0)