Skip to content

Commit b4a5480

Browse files
authored
Merge pull request mouredev#6974 from duendeintemporal/main
#26 - javascript
2 parents 17f782c + 944d61e commit b4a5480

File tree

2 files changed

+493
-0
lines changed

2 files changed

+493
-0
lines changed
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
//#26 - Principio SOLID de Responsabilidad Única (Single Responsibility Principle, SRP)
2+
//Bibliografy: The Web Development Glossary (Jens Oliver Meiert) (Z-Library)
3+
//GPT
4+
/*
5+
* EJERCICIO:
6+
* Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility
7+
* Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento
8+
* de forma correcta e incorrecta.
9+
*
10+
* DIFICULTAD EXTRA (opcional):
11+
* Desarrolla un sistema de gestión para una biblioteca. El sistema necesita
12+
* manejar diferentes aspectos como el registro de libros, la gestión de usuarios
13+
* y el procesamiento de préstamos de libros.
14+
* Requisitos:
15+
* 1. Registrar libros: El sistema debe permitir agregar nuevos libros con
16+
* información básica como título, autor y número de copias disponibles.
17+
* 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con
18+
* información básica como nombre, número de identificación y correo electrónico.
19+
* 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios
20+
* tomar prestados y devolver libros.
21+
* Instrucciones:
22+
* 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje
23+
* los tres aspectos mencionados anteriormente (registro de libros, registro de
24+
* usuarios y procesamiento de préstamos).
25+
* 2. Refactoriza el código: Separa las responsabilidades en diferentes clases
26+
* siguiendo el Principio de Responsabilidad Única.
27+
*/
28+
29+
30+
/* Single Responsibility Principle
31+
A computer programming principle that states that every module, class, or
32+
function should have responsibility over a single part of the functionality
33+
provided by the software, and that responsibility should be entirely
34+
encapsulated by the module, class, or function. All its services should be
35+
narrowly aligned with that responsibility. */
36+
37+
//Not Following the Single Responsibility Principle (SRP)
38+
39+
let log = console.log;
40+
41+
window.addEventListener('load', ()=>{
42+
const body = document.querySelector('body');
43+
const title = document.createElement('h1');
44+
45+
body.style.setProperty('background', '#000');
46+
body.style.setProperty('text-align', 'center');
47+
48+
title.textContent = 'Retosparaprogramadores #26.';
49+
title.style.setProperty('font-size', '3.5vmax');
50+
title.style.setProperty('color', '#fff');
51+
title.style.setProperty('line-height', '100vh');
52+
53+
body.appendChild(title);
54+
55+
setTimeout(()=>{
56+
alert('Retosparaprogramadores #26. Please open the Browser Developer Tools.');
57+
}, 2000);
58+
log( 'Retosparaprogramadores #26');
59+
});
60+
61+
class Library {
62+
constructor() {
63+
this.books = [];
64+
this.users = [];
65+
this.loans = [];
66+
}
67+
68+
addBook(title, author, copies) {
69+
this.books.push({ title, author, copies });
70+
}
71+
72+
registerUser(name, id, email) {
73+
this.users.push({ name, id, email });
74+
}
75+
76+
loanBook(userId, bookTitle) {
77+
const user = this.users.find(u => u.id === userId);
78+
const book = this.books.find(b => b.title === bookTitle);
79+
80+
if (user && book && book.copies > 0) {
81+
this.loans.push({ userId, bookTitle });
82+
book.copies--;
83+
log(`Book "${bookTitle}" loaned to ${user.name}`);
84+
} else {
85+
log("Loan failed: User or book not found, or no copies available.");
86+
}
87+
}
88+
}
89+
90+
91+
const library = new Library();
92+
library.addBook("Learn Bash the Hard Way", "Ian Miell", 2);
93+
library.addBook("MATLAB Notes for Professionals", "GoalKicker.com", 4);
94+
library.registerUser("Royer Rabit", "006", "[email protected]");
95+
library.loanBook("006", "MATLAB Notes for Professionals"); //Book "MATLAB Notes for Professionals" loaned to Royer Rabit
96+
97+
98+
//Extra difiiculty Excercise
99+
//Following the Single Responsibility Principle (SRP)
100+
101+
class Book {
102+
constructor(title, author, copies) {
103+
this.title = title;
104+
this.author = author;
105+
this.copies = copies;
106+
}
107+
}
108+
109+
class User {
110+
constructor(name, id, email) {
111+
this.name = name;
112+
this.id = id;
113+
this.email = email;
114+
}
115+
}
116+
117+
class BookManager {
118+
constructor() {
119+
this.books = [];
120+
}
121+
122+
addBook(title, author, copies) {
123+
this.books.push(new Book(title, author, copies));
124+
}
125+
126+
getBooks() {
127+
return this.books;
128+
}
129+
130+
findBook(title) {
131+
return this.books.find(b => b.title === title);
132+
}
133+
134+
increaseCopies(bookTitle) {
135+
const book = this.findBook(bookTitle);
136+
if (book) {
137+
book.copies++;
138+
}
139+
}
140+
}
141+
142+
function searchBooksByPartialTitle(books, searchTerm) {
143+
return books.filter(book =>
144+
book.title.toLowerCase().includes(searchTerm.toLowerCase())
145+
);
146+
}
147+
148+
class UserManager {
149+
constructor() {
150+
this.users = [];
151+
}
152+
153+
registerUser(name, id, email) {
154+
this.users.push(new User(name, id, email));
155+
}
156+
157+
findUser(id) {
158+
return this.users.find(u => u.id === id);
159+
}
160+
}
161+
162+
class LoanManager {
163+
constructor() {
164+
this.loans = [];
165+
this.nextLoanId = 1;
166+
}
167+
168+
loanBook(user, book) {
169+
if (book.copies > 0) {
170+
const loanId = this.nextLoanId++;
171+
this.loans.push({loanId, userId: user.id, bookTitle: book.title });
172+
book.copies--;
173+
log(`Book "${book.title}" loaned to ${user.name} with Loan ID: ${loanId}`);
174+
} else {
175+
log("Loan failed: No copies available.");
176+
}
177+
}
178+
179+
returnBook(loanId, bookManager) {
180+
const loanIndex = this.loans.findIndex(loan => loan.loanId === loanId);
181+
182+
if (loanIndex !== -1) {
183+
const loan = this.loans[loanIndex];
184+
const book = bookManager.findBook(loan.bookTitle);
185+
if (book) {
186+
book.copies++;
187+
}
188+
189+
// Remove the loan from the loans array
190+
this.loans.splice(loanIndex, 1);
191+
log(`Book "${loan.bookTitle}" returned with Loan ID: ${loanId}`);
192+
} else {
193+
log("Return failed: No loan record found for this Loan ID.");
194+
}
195+
}
196+
197+
getLoansByPartialBookTitle(searchTerm, userId) {
198+
return this.loans.filter(loan =>
199+
loan.bookTitle.toLowerCase().includes(searchTerm.toLowerCase()) && loan.userId === userId
200+
);
201+
}
202+
}
203+
204+
205+
const bookManager = new BookManager();
206+
const userManager = new UserManager();
207+
const loanManager = new LoanManager();
208+
209+
bookManager.addBook("300 JavaScript Interview Mastery Questions Dive Deep into JavaScript Theory, Syntax, and APIs, and Interview with Confidence", "Middaugh, Jonathan", 3);
210+
bookManager.addBook("Javascript Interview Questions and Answers", "Bandal, Pratik", 7);
211+
bookManager.addBook("100 MOST ASKED JOB READY QUESTIONS ANSWERS IN THE TECH SPACE Here are the most asked questions in PYTHON, SQL, JAVASCRIPT...", "Aimee Mills", 2);
212+
userManager.registerUser("Niko Zen", "008", "[email protected]");
213+
214+
const searchTerm1 = "JavaScript";
215+
const searchTerm2 = "Interview Questions";
216+
217+
const searchResults1 = searchBooksByPartialTitle(bookManager.getBooks(), searchTerm1);
218+
const searchResults2 = searchBooksByPartialTitle(bookManager.getBooks(), searchTerm2);
219+
220+
log(searchResults1);
221+
/*
222+
Book {title: '300 JavaScript Interview Mastery Questions Dive De…, Syntax, and APIs, and Interview with Confidence', author: 'Middaugh, Jonathan', copies: 3}
223+
Book {title: 'Javascript Interview Questions and Answers', author: 'Bandal, Pratik', copies: 7}
224+
Book {title: '100 MOST ASKED JOB READY QUESTIONS ANSWERS IN THE …ost asked questions in PYTHON, SQL, JAVASCRIPT...', author: 'Aimee Mills', copies: 2}
225+
*/
226+
log(searchResults2);
227+
/* {author:"Bandal, Pratik", copies:7, title:"Javascript Interview Questions and Answers"} */
228+
229+
const user = userManager.findUser("008");
230+
const bookTitle = searchResults1[2]?.title;
231+
const book = bookManager.findBook(bookTitle);
232+
233+
if (book) {
234+
loanManager.loanBook(user, book); // Book "100 MOST ASKED JOB READY QUESTIONS ANSWERS IN THE TECH SPACE Here are the most asked questions in PYTHON, SQL, JAVASCRIPT..." loaned to Niko Zen with Loan ID: 1
235+
const loans = loanManager.getLoansByPartialBookTitle(book.title, user.id);
236+
loanManager.returnBook(loans[0].loanId, bookManager); // Book "100 MOST ASKED JOB READY QUESTIONS ANSWERS IN THE TECH SPACE Here are the most asked questions in PYTHON, SQL, JAVASCRIPT..." returned with Loan ID: 1
237+
} else {
238+
log("Book not found for loan.");
239+
}
240+

0 commit comments

Comments
 (0)