Skip to content

Commit 374ab6c

Browse files
authored
Merge pull request mouredev#6924 from duendeintemporal/main
#25 - javascript
2 parents 800dee9 + d598a99 commit 374ab6c

File tree

5 files changed

+474
-3
lines changed

5 files changed

+474
-3
lines changed

Roadmap/18 - CONJUNTOS/javascript/duendeintemporal.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
//#18 - CONJUNTOS
2-
/*
3-
* EJERCICIO:
2+
/* * EJERCICIO:
43
* Utilizando tu lenguaje crea un conjunto de datos y realiza las siguientes
54
* operaciones (debes utilizar una estructura que las soporte):
65
* - Añade un elemento al final.

Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/javascript/duendeintemporal.js

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,97 @@ const addOddNums = (n)=> {
9898

9999
log(addOddNums(100)); // 2500
100100

101-
//There are some built-in array methods, forEach, map, reduce, some... that provide something like a for/of loop as a higher-order function.
101+
//There are some built-in array methods, forEach, map, reduce, some... that provide something like a for/of loop as a higher-order function.
102+
103+
//EXTRA DIFICULTY EXERCISE
104+
105+
// Student class definition
106+
class Student {
107+
constructor(name, birthday, calification) {
108+
this.name = name;
109+
this.birthday = new Date(birthday);
110+
this.calification = calification;
111+
}
112+
113+
getName() {
114+
return this.name;
115+
}
116+
117+
getBirthday() {
118+
return this.birthday;
119+
}
120+
121+
getCalification() {
122+
return this.calification;
123+
}
124+
125+
setName(name) {
126+
this.name = name;
127+
}
128+
129+
setBirthday(birthday) {
130+
this.birthday = new Date(birthday);
131+
}
132+
133+
setCalification(calification) {
134+
this.calification = calification;
135+
}
136+
}
137+
138+
// List of students
139+
let students = [
140+
new Student('Juan Rulfo', '1986-06-07', 7),
141+
new Student('Moure Dev', '1982-03-08', 8.5),
142+
new Student('Calvin Maker', '2000-04-02', 9.8),
143+
new Student('Adela Jimenez', '1976-01-09', 7.9),
144+
new Student('Crist Renegate', '2001-07-09', 5),
145+
new Student('Gautama Buda', '0623-05-23', 9),
146+
new Student('Niko Zen', '1983-08-08', 10)
147+
];
148+
149+
// Function to get a list of students with their average grades
150+
const studentsAverageList = (arr) => {
151+
return arr.map(student => ({
152+
name: student.getName(),
153+
average: student.getCalification()
154+
})).sort((a, b) => b.average - a.average);
155+
};
156+
157+
// Function to get a list of students with grades of 9 or higher
158+
const higherThan9Students = (arr) => {
159+
return arr.filter(student => student.getCalification() >= 9)
160+
.map(student => student.getName());
161+
};
162+
163+
// Function to sort students by their birth date
164+
const sortStudentsByBirthday = (arr) => {
165+
return arr.slice().sort((a, b) => a.getBirthday() - b.getBirthday())
166+
.map(student => student.getName());
167+
};
168+
169+
// Function to find the highest grade among all students
170+
const highestCalification = (arr) => {
171+
return Math.max(...arr.map(student => student.getCalification()));
172+
};
173+
174+
// Execute the functions and store the results
175+
let averageList = studentsAverageList(students);
176+
let bestStudents = higherThan9Students(students);
177+
let sortedStudents = sortStudentsByBirthday(students);
178+
let highestGrade = highestCalification(students);
179+
180+
// Display the results in the console
181+
log("Average grades:", averageList); /*
182+
Average grades:
183+
Array(7) [ {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
184+
0: Object { name: "Niko Zen", average: 10 }
185+
1: Object { name: "Calvin Maker", average: 9.8 }
186+
2: Object { name: "Gautama Buda", average: 9 }
187+
3: Object { name: "Moure Dev", average: 8.5 }
188+
4: Object { name: "Adela Jimenez", average: 7.9 }
189+
5: Object { name: "Juan Rulfo", average: 7 }
190+
6: Object { name: "Crist Renegate", average: 5 }
191+
*/
192+
log("Best students (9 or higher):", bestStudents); // Best students (9 or higher): ['Calvin Maker', 'Gautama Buda', 'Niko Zen']
193+
log("Students sorted by birth date:", sortedStudents); // Students sorted by birth date: (7) ['Gautama Buda', 'Adela Jimenez', 'Moure Dev', 'Niko Zen', 'Juan Rulfo', 'Calvin Maker', 'Crist Renegate']
194+
log("Highest grade:", highestGrade); // Highest grade: 10
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
//#23 - PATRONES DE DISEÑO: SINGLETON
2+
/*
3+
* EJERCICIO:
4+
* Explora el patrón de diseño "singleton" y muestra cómo crearlo
5+
* con un ejemplo genérico.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Utiliza el patrón de diseño "singleton" para representar una clase que
9+
* haga referencia a la sesión de usuario de una aplicación ficticia.
10+
* La sesión debe permitir asignar un usuario (id, username, nombre y email),
11+
* recuperar los datos del usuario y borrar los datos de la sesión.
12+
*/
13+
14+
let log = console.log;
15+
16+
window.addEventListener('load', ()=>{
17+
const body = document.querySelector('body');
18+
const title = document.createElement('h1');
19+
20+
body.style.setProperty('background', '#000');
21+
body.style.setProperty('text-align', 'center');
22+
23+
title.textContent = 'Retosparaprogramadores #23.';
24+
title.style.setProperty('font-size', '3.5vmax');
25+
title.style.setProperty('color', '#fff');
26+
title.style.setProperty('line-height', '100vh');
27+
28+
body.appendChild(title);
29+
30+
setTimeout(()=>{
31+
alert('Retosparaprogramadores #23. Please open the Browser Developer Tools.');
32+
}, 2000);
33+
log( 'Retosparaprogramadores #23');
34+
});
35+
36+
37+
/*
38+
The Singleton design pattern ensures that a class has a single instance and provides a global point of access to that instance. Below, I will show you how to implement the Singleton pattern in JavaScript, followed by an example that represents a class for managing user sessions.
39+
40+
Implementation of the Singleton Pattern
41+
*/
42+
43+
class Singleton{
44+
constructor() {
45+
if (Singleton.instance) {
46+
return Singleton.instance;
47+
}
48+
Singleton.instance = this;
49+
// Initialize any properties you need here
50+
}
51+
52+
// Example method
53+
someMethod() {
54+
log("This is a method of the singleton.");
55+
}
56+
}
57+
58+
// Using the Singleton
59+
const instance1 = new Singleton();
60+
const instance2 = new Singleton();
61+
62+
//Note: both variables point to the same instance
63+
log(instance1 === instance2); // true
64+
65+
//EXTRA DIFICULTY EXERCISE
66+
67+
class UserSession {
68+
constructor() {
69+
if (UserSession.instance) {
70+
return UserSession.instance;
71+
}
72+
UserSession.instance = this;
73+
this.user = null;
74+
}
75+
76+
setUser(id, username, name, email) {
77+
this.user = { id, username, name, email };
78+
}
79+
80+
getUser() {
81+
return this.user;
82+
}
83+
84+
clearSession() {
85+
this.user = null;
86+
}
87+
}
88+
89+
const session1 = new UserSession();
90+
session1.setUser(1, 'FritzCat', 'Fritz Cat', '[email protected]');
91+
92+
log(session1.getUser()); // Object { id: 1, username: "FritzCat", name: "Fritz Cat", email: "fritzcat@proton.me" }
93+
94+
const session2 = new UserSession();
95+
log(session2.getUser()); // Object { id: 1, username: "FritzCat", name: "Fritz Cat", email: "fritzcat@proton.me" }
96+
97+
session2.clearSession();
98+
log(session1.getUser()); // null
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
//#24 - PATRONES DE DISEÑO: DECORADORES
2+
/*
3+
* EJERCICIO:
4+
* Explora el concepto de "decorador" y muestra cómo crearlo
5+
* con un ejemplo genérico.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Crea un decorador que sea capaz de contabilizar cuántas veces
9+
* se ha llamado a una función y aplícalo a una función de tu elección.
10+
*/
11+
12+
let log = console.log;
13+
14+
window.addEventListener('load', ()=>{
15+
const body = document.querySelector('body');
16+
const title = document.createElement('h1');
17+
18+
body.style.setProperty('background', '#000');
19+
body.style.setProperty('text-align', 'center');
20+
21+
title.textContent = 'Retosparaprogramadores #24.';
22+
title.style.setProperty('font-size', '3.5vmax');
23+
title.style.setProperty('color', '#fff');
24+
title.style.setProperty('line-height', '100vh');
25+
26+
body.appendChild(title);
27+
28+
setTimeout(()=>{
29+
alert('Retosparaprogramadores #24. Please open the Browser Developer Tools.');
30+
}, 2000);
31+
log( 'Retosparaprogramadores #24');
32+
});
33+
34+
35+
/* The decorator pattern is a structural design pattern that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. In JavaScript, decorators can be implemented using higher-order functions. */
36+
37+
// Generic decorator function
38+
function decorator(fn) {
39+
return function(...args) {
40+
log("Before calling the function");
41+
const result = fn(...args);
42+
log("After calling the function");
43+
return result;
44+
};
45+
}
46+
47+
// Decorator to log execution time
48+
function logExecutionTime(fn) {
49+
return async function(...args) {
50+
const start = performance.now(); // Start time
51+
const result = await fn(...args);
52+
const end = performance.now(); // End time
53+
log(`Execution time for ${fn.name}: ${end - start} milliseconds`);
54+
return result;
55+
};
56+
}
57+
58+
// Example function that simulates a time-consuming task
59+
function fetchData() {
60+
return new Promise((resolve) => {
61+
setTimeout(() => {
62+
resolve("Data fetched!");
63+
}, 3000);
64+
});
65+
}
66+
67+
// Decorated function
68+
const loggedFetchData = logExecutionTime(fetchData); // Execution time for fetchData: 10732 milliseconds
69+
70+
//Note: the fetchData() has delate of 3 seconds so the previus msj will be logged at the end after that time.
71+
72+
// Using the decorated function
73+
loggedFetchData().then(result => log(result)); // Data fetched!
74+
75+
76+
//EXTRA DIFICULTY EXERCISE
77+
78+
// Decorator to count function calls
79+
function countCalls(fn) {
80+
let callCount = 0; // Private variable to keep track of calls through closure
81+
82+
return function(...args) {
83+
callCount++;
84+
log(`Function has been called ${callCount} times.`);
85+
return fn(...args);
86+
};
87+
}
88+
89+
// Original function
90+
function hiGirl() {
91+
log('Hi Girl! \uD83C\uDF39');
92+
return '\uD83C\uDF3C';
93+
}
94+
95+
// Decorated function
96+
const countedhiGirl = countCalls(hiGirl);
97+
98+
// Using the decorated function
99+
log(countedhiGirl()); // Function has been called 1 times. Hi Girl! 🌹
100+
log(countedhiGirl()); // Function has been called 2 times. Hi Girl! 🌹
101+
log(countedhiGirl()); // Function has been called 3 times. Hi Girl! 🌹
102+
103+
// Trying to access countedhiGirl directly will result in an error
104+
// log(countedhiGirl); // Uncaught ReferenceError: countedhiGirl is not defined
105+
106+
107+
108+
/* NOTE: When you define a function inside another function, the inner function creates a private scope. This means that the inner function has access to the variables and parameters of the outer function, but those variables are not accessible from outside the outer function. This is a key feature of closures in JavaScript.
109+
110+
Explanation of Private Scope with Closures
111+
In the context of the decorator pattern, this private scope allows us to maintain state (like the callCount in the counting decorator) without exposing it to the outside world. Here’s a breakdown of how this works:
112+
113+
Closure: When the inner function is returned from the outer function, it retains access to the outer function's variables. This is known as a closure. The inner function can use and modify these variables even after the outer function has finished executing.
114+
Private Variables: Variables defined in the outer function (like callCount) are not accessible from outside the function. This means that you cannot directly modify or read callCount from outside the countCalls function, which effectively makes it private.*/

0 commit comments

Comments
 (0)