Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Roadmap/18 - CONJUNTOS/javascript/duendeintemporal.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//#18 - CONJUNTOS
/*
* EJERCICIO:
/* * EJERCICIO:
* Utilizando tu lenguaje crea un conjunto de datos y realiza las siguientes
* operaciones (debes utilizar una estructura que las soporte):
* - Añade un elemento al final.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,97 @@ const addOddNums = (n)=> {

log(addOddNums(100)); // 2500

//There are some built-in array methods, forEach, map, reduce, some... that provide something like a for/of loop as a higher-order function.
//There are some built-in array methods, forEach, map, reduce, some... that provide something like a for/of loop as a higher-order function.

//EXTRA DIFICULTY EXERCISE

// Student class definition
class Student {
constructor(name, birthday, calification) {
this.name = name;
this.birthday = new Date(birthday);
this.calification = calification;
}

getName() {
return this.name;
}

getBirthday() {
return this.birthday;
}

getCalification() {
return this.calification;
}

setName(name) {
this.name = name;
}

setBirthday(birthday) {
this.birthday = new Date(birthday);
}

setCalification(calification) {
this.calification = calification;
}
}

// List of students
let students = [
new Student('Juan Rulfo', '1986-06-07', 7),
new Student('Moure Dev', '1982-03-08', 8.5),
new Student('Calvin Maker', '2000-04-02', 9.8),
new Student('Adela Jimenez', '1976-01-09', 7.9),
new Student('Crist Renegate', '2001-07-09', 5),
new Student('Gautama Buda', '0623-05-23', 9),
new Student('Niko Zen', '1983-08-08', 10)
];

// Function to get a list of students with their average grades
const studentsAverageList = (arr) => {
return arr.map(student => ({
name: student.getName(),
average: student.getCalification()
})).sort((a, b) => b.average - a.average);
};

// Function to get a list of students with grades of 9 or higher
const higherThan9Students = (arr) => {
return arr.filter(student => student.getCalification() >= 9)
.map(student => student.getName());
};

// Function to sort students by their birth date
const sortStudentsByBirthday = (arr) => {
return arr.slice().sort((a, b) => a.getBirthday() - b.getBirthday())
.map(student => student.getName());
};

// Function to find the highest grade among all students
const highestCalification = (arr) => {
return Math.max(...arr.map(student => student.getCalification()));
};

// Execute the functions and store the results
let averageList = studentsAverageList(students);
let bestStudents = higherThan9Students(students);
let sortedStudents = sortStudentsByBirthday(students);
let highestGrade = highestCalification(students);

// Display the results in the console
log("Average grades:", averageList); /*
Average grades:
Array(7) [ {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
0: Object { name: "Niko Zen", average: 10 }
1: Object { name: "Calvin Maker", average: 9.8 }
2: Object { name: "Gautama Buda", average: 9 }
3: Object { name: "Moure Dev", average: 8.5 }
4: Object { name: "Adela Jimenez", average: 7.9 }
5: Object { name: "Juan Rulfo", average: 7 }
6: Object { name: "Crist Renegate", average: 5 }
*/
log("Best students (9 or higher):", bestStudents); // Best students (9 or higher): ['Calvin Maker', 'Gautama Buda', 'Niko Zen']
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']
log("Highest grade:", highestGrade); // Highest grade: 10
98 changes: 98 additions & 0 deletions Roadmap/23 - SINGLETON/javascript/duendeintemporal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//#23 - PATRONES DE DISEÑO: SINGLETON
/*
* EJERCICIO:
* Explora el patrón de diseño "singleton" y muestra cómo crearlo
* con un ejemplo genérico.
*
* DIFICULTAD EXTRA (opcional):
* Utiliza el patrón de diseño "singleton" para representar una clase que
* haga referencia a la sesión de usuario de una aplicación ficticia.
* La sesión debe permitir asignar un usuario (id, username, nombre y email),
* recuperar los datos del usuario y borrar los datos de la sesión.
*/

let log = console.log;

window.addEventListener('load', ()=>{
const body = document.querySelector('body');
const title = document.createElement('h1');

body.style.setProperty('background', '#000');
body.style.setProperty('text-align', 'center');

title.textContent = 'Retosparaprogramadores #23.';
title.style.setProperty('font-size', '3.5vmax');
title.style.setProperty('color', '#fff');
title.style.setProperty('line-height', '100vh');

body.appendChild(title);

setTimeout(()=>{
alert('Retosparaprogramadores #23. Please open the Browser Developer Tools.');
}, 2000);
log( 'Retosparaprogramadores #23');
});


/*
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.

Implementation of the Singleton Pattern
*/

class Singleton{
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
// Initialize any properties you need here
}

// Example method
someMethod() {
log("This is a method of the singleton.");
}
}

// Using the Singleton
const instance1 = new Singleton();
const instance2 = new Singleton();

//Note: both variables point to the same instance
log(instance1 === instance2); // true

//EXTRA DIFICULTY EXERCISE

class UserSession {
constructor() {
if (UserSession.instance) {
return UserSession.instance;
}
UserSession.instance = this;
this.user = null;
}

setUser(id, username, name, email) {
this.user = { id, username, name, email };
}

getUser() {
return this.user;
}

clearSession() {
this.user = null;
}
}

const session1 = new UserSession();
session1.setUser(1, 'FritzCat', 'Fritz Cat', '[email protected]');

log(session1.getUser()); // Object { id: 1, username: "FritzCat", name: "Fritz Cat", email: "[email protected]" }

const session2 = new UserSession();
log(session2.getUser()); // Object { id: 1, username: "FritzCat", name: "Fritz Cat", email: "[email protected]" }

session2.clearSession();
log(session1.getUser()); // null
114 changes: 114 additions & 0 deletions Roadmap/24 - DECORADORES/javascript/duendeintemporal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
//#24 - PATRONES DE DISEÑO: DECORADORES
/*
* EJERCICIO:
* Explora el concepto de "decorador" y muestra cómo crearlo
* con un ejemplo genérico.
*
* DIFICULTAD EXTRA (opcional):
* Crea un decorador que sea capaz de contabilizar cuántas veces
* se ha llamado a una función y aplícalo a una función de tu elección.
*/

let log = console.log;

window.addEventListener('load', ()=>{
const body = document.querySelector('body');
const title = document.createElement('h1');

body.style.setProperty('background', '#000');
body.style.setProperty('text-align', 'center');

title.textContent = 'Retosparaprogramadores #24.';
title.style.setProperty('font-size', '3.5vmax');
title.style.setProperty('color', '#fff');
title.style.setProperty('line-height', '100vh');

body.appendChild(title);

setTimeout(()=>{
alert('Retosparaprogramadores #24. Please open the Browser Developer Tools.');
}, 2000);
log( 'Retosparaprogramadores #24');
});


/* 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. */

// Generic decorator function
function decorator(fn) {
return function(...args) {
log("Before calling the function");
const result = fn(...args);
log("After calling the function");
return result;
};
}

// Decorator to log execution time
function logExecutionTime(fn) {
return async function(...args) {
const start = performance.now(); // Start time
const result = await fn(...args);
const end = performance.now(); // End time
log(`Execution time for ${fn.name}: ${end - start} milliseconds`);
return result;
};
}

// Example function that simulates a time-consuming task
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 3000);
});
}

// Decorated function
const loggedFetchData = logExecutionTime(fetchData); // Execution time for fetchData: 10732 milliseconds

//Note: the fetchData() has delate of 3 seconds so the previus msj will be logged at the end after that time.

// Using the decorated function
loggedFetchData().then(result => log(result)); // Data fetched!


//EXTRA DIFICULTY EXERCISE

// Decorator to count function calls
function countCalls(fn) {
let callCount = 0; // Private variable to keep track of calls through closure

return function(...args) {
callCount++;
log(`Function has been called ${callCount} times.`);
return fn(...args);
};
}

// Original function
function hiGirl() {
log('Hi Girl! \uD83C\uDF39');
return '\uD83C\uDF3C';
}

// Decorated function
const countedhiGirl = countCalls(hiGirl);

// Using the decorated function
log(countedhiGirl()); // Function has been called 1 times. Hi Girl! 🌹
log(countedhiGirl()); // Function has been called 2 times. Hi Girl! 🌹
log(countedhiGirl()); // Function has been called 3 times. Hi Girl! 🌹

// Trying to access countedhiGirl directly will result in an error
// log(countedhiGirl); // Uncaught ReferenceError: countedhiGirl is not defined



/* 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.

Explanation of Private Scope with Closures
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:

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.
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.*/
Loading