Skip to content

Commit 5e2df21

Browse files
authored
Merge pull request mouredev#7499 from Kenysdev/06_10.js
#6 - javascript -> #10
2 parents d52645c + 9f2f38c commit 5e2df21

File tree

5 files changed

+844
-0
lines changed

5 files changed

+844
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
_____________________________________
3+
https://github.com/kenysdev
4+
2024 - JavaScript
5+
_______________________________________
6+
#06 RECURSIVIDAD
7+
---------------------------------------
8+
* EJERCICIO:
9+
* Entiende el concepto de recursividad creando una función recursiva que imprima
10+
* números del 100 al 0.
11+
*
12+
* DIFICULTAD EXTRA (opcional):
13+
* Utiliza el concepto de recursividad para:
14+
* - Calcular el factorial de un número concreto (la función recibe ese número).
15+
* - Calcular el valor de un elemento concreto (según su posición) en la
16+
* sucesión de Fibonacci (la función recibe la posición).
17+
*/
18+
19+
// ________________________________________________________
20+
function num(n) {
21+
console.log(n);
22+
// Base case
23+
if (n > 0) {
24+
num(n - 1);
25+
}
26+
}
27+
num(100);
28+
29+
// ________________________________________________________
30+
// DIFICULTAD EXTRA
31+
32+
// Calcular el factorial de un número concreto
33+
// 4! = 4 * 3 * 2 * 1 = 24
34+
function factorial(n) {
35+
if (n !== 0) {
36+
return n * factorial(n - 1);
37+
} else {
38+
return 1;
39+
}
40+
/* explicación:
41+
factorial(4)
42+
| = 24
43+
return 4 * factorial(3) -> (4 * 6)
44+
| = 6
45+
return 3 * factorial(2) -> (3 * 2)
46+
| = 2
47+
return 2 * factorial(1) -> (2 * 1)
48+
| = 1
49+
return 1 * factorial(0) -> (1 * 1)
50+
| = return 1 -> base case
51+
*/
52+
}
53+
54+
// Calcular el valor de un elemento concreto (según su posición) en la sucesión de Fibonacci.
55+
// n : |0|1|2|3|4|5|6|..
56+
// fb: |0|1|1|2|3|5|8|..
57+
// |+|=^ |+|=^ ..
58+
function fibonacci(n) {
59+
if (n <= 1) {
60+
return n;
61+
} else {
62+
return fibonacci(n - 1) + fibonacci(n - 2);
63+
/* explicación:
64+
return 3
65+
fibonacci(3) / \ fibonacci(2)
66+
/ \ =2 + / \ =1
67+
fibonacci(2) + fibonacci(1) fibonacci(1) + fibonacci(0) -> base case
68+
/ \ =1
69+
fibonacci(1) + fibonacci(0) -> base case
70+
*/
71+
}
72+
}
73+
74+
console.log(`Factorial de 4: \n${factorial(4)}`);
75+
console.log(`Valor según posición 4 en Fibonacci:\n${fibonacci(4)}`);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
/*
2+
_____________________________________
3+
https://github.com/kenysdev
4+
2024 - JavaScript
5+
_______________________________________
6+
#07 PILAS Y COLAS
7+
---------------------------------------
8+
* EJERCICIO:
9+
* Implementa los mecanismos de introducción y recuperación de elementos propios de las
10+
* pilas (stacks - LIFO) y las colas (queue - FIFO) utilizando una estructura de array
11+
* o lista (dependiendo de las posibilidades de tu lenguaje).
12+
*
13+
* DIFICULTAD EXTRA (opcional):
14+
* - Utilizando la implementación de pila y cadenas de texto, simula el mecanismo Forward/atrás
15+
* de un navegador web. Crea un programa en el que puedas navegar a una página o indicarle
16+
* que te quieres desplazar Forward o atrás, mostrando en cada caso el nombre de la web.
17+
* Las palabras "Forward", "atrás" desencadenan esta acción, el resto se interpreta como
18+
* el nombre de una nueva web.
19+
* - Utilizando la implementación de cola y cadenas de texto, simula el mecanismo de una
20+
* impresora compartida que recibe documentos y los imprime cuando así se le indica.
21+
* La palabra "imprimir" imprime un elemento de la cola, el resto de palabras se
22+
* interpretan como nombres de documentos.
23+
*/
24+
25+
// ________________________________________________________
26+
// Pilas (Stack - LIFO):
27+
// - Estructura de datos que sigue el principio LIFO (Last In, First Out).
28+
// - El último elemento agregado es el primero en ser retirado.
29+
30+
class Stack {
31+
constructor() {
32+
this.elements = [];
33+
}
34+
35+
// Total de elementos
36+
get length() {
37+
return this.elements.length;
38+
}
39+
40+
// Verificar si la pila está vacía
41+
isEmpty() {
42+
return this.length === 0;
43+
}
44+
45+
// Agregar un elemento
46+
push(item) {
47+
this.elements.push(item);
48+
}
49+
50+
// Agregar múltiples elementos
51+
pushBatch(items) {
52+
this.elements.push(...items);
53+
}
54+
55+
// Eliminar y obtener el elemento superior
56+
pop() {
57+
return this.isEmpty() ? null : this.elements.pop();
58+
}
59+
60+
// Obtener el elemento superior sin eliminarlo
61+
peek() {
62+
return this.isEmpty() ? null : this.elements[this.elements.length - 1];
63+
}
64+
65+
// Obtener la pila como tupla
66+
toArray() {
67+
return [...this.elements].reverse();
68+
}
69+
70+
// Vaciar la pila
71+
clear() {
72+
this.elements = [];
73+
}
74+
}
75+
76+
// ________________________________________________________
77+
// Ejercicio: Historial de navegación
78+
79+
const MsgNav = `
80+
Historial de navegación:
81+
-------------------------------------------------
82+
Usar: "<" para página anterior.
83+
">" para página Forward.
84+
"h" Ver historial completo.
85+
"x" para salir.
86+
Escribir web para agregar:
87+
-------------------------------------------------`;
88+
89+
function NavHistory() {
90+
const BackHistory = new Stack();
91+
const forwardHistory = new Stack();
92+
const history = new Stack();
93+
history.push("Inicio");
94+
95+
const ShowHistory = () => {
96+
console.log(MsgNav);
97+
ShowStatus(history.peek());
98+
SelectAction();
99+
};
100+
101+
const ShowStatus = (url) => {
102+
console.log(`(${BackHistory.length}) <- Atrás <- [Actual: ${url}] -> Forward -> (${forwardHistory.length})`);
103+
};
104+
105+
const Back = () => {
106+
if (!BackHistory.isEmpty()) {
107+
forwardHistory.push(history.pop());
108+
history.push(BackHistory.pop());
109+
ShowStatus(history.peek());
110+
} else {
111+
console.log("No hay página previa.");
112+
}
113+
SelectAction();
114+
};
115+
116+
const Forward = () => {
117+
if (!forwardHistory.isEmpty()) {
118+
BackHistory.push(history.pop());
119+
history.push(forwardHistory.pop());
120+
ShowStatus(history.peek());
121+
} else {
122+
console.log("No hay página siguiente.");
123+
}
124+
SelectAction();
125+
};
126+
127+
const NewWeb = (url) => {
128+
BackHistory.push(history.peek());
129+
forwardHistory.clear();
130+
history.push(url);
131+
ShowStatus(history.peek());
132+
SelectAction();
133+
};
134+
135+
const PrintHistory = () => {
136+
const historial = history.toArray();
137+
console.log(historial.length ? historial.join(" -> ") : "Historial vacío.");
138+
SelectAction();
139+
};
140+
141+
const SelectAction = () => {
142+
console.log("____________");
143+
rl.question("Acción: ", (option) => {
144+
switch (option) {
145+
case "<":
146+
Back();
147+
break;
148+
case ">":
149+
Forward();
150+
break;
151+
case "h":
152+
PrintHistory();
153+
break;
154+
case "x":
155+
rl.close;
156+
main();
157+
return;
158+
default:
159+
NewWeb(option);
160+
}
161+
});
162+
};
163+
164+
ShowHistory();
165+
}
166+
167+
// ________________________________________________________
168+
// Colas (Queue - FIFO):
169+
// - Estructura de datos que sigue el principio FIFO (First In, First Out).
170+
// - El primer elemento agregado es el primero en ser retirado.
171+
class Queue {
172+
constructor() {
173+
this.elements = [];
174+
}
175+
176+
// Total de elementos
177+
get length() {
178+
return this.elements.length;
179+
}
180+
181+
// Verificar si la cola está vacía
182+
isEmpty() {
183+
return this.length === 0;
184+
}
185+
186+
// Agregar un elemento
187+
enqueue(item) {
188+
this.elements.push(item);
189+
}
190+
191+
// Agregar múltiples elementos
192+
enqueueAll(items) {
193+
this.elements.push(...items);
194+
}
195+
196+
// Eliminar y devolver el primer elemento
197+
dequeue() {
198+
return this.isEmpty() ? null : this.elements.shift();
199+
}
200+
201+
// Obtener el primer elemento sin eliminarlo
202+
peek() {
203+
return this.isEmpty() ? null : this.elements[0];
204+
}
205+
206+
// Obtener la cola como tupla
207+
toArray() {
208+
return [...this.elements];
209+
}
210+
211+
// Vaciar la cola
212+
clear() {
213+
this.elements = [];
214+
}
215+
}
216+
217+
// ________________________________________________________
218+
// Ejercicio: Simulador de impresora
219+
220+
const mensajeImpresora = `
221+
------------------------------------------------
222+
Usar: "p" Imprimir.
223+
"l" Ver documentos pendientes.
224+
"x" para salir.
225+
Escribir nombre de documento para enviar a cola:
226+
------------------------------------------------`;
227+
228+
function QueuePrinter() {
229+
const docQueue = new Queue();
230+
docQueue.enqueueAll(["a.pdf", "b.txt", "c.docx"]);
231+
232+
const PrintDoc = () => {
233+
if (!docQueue.isEmpty()) {
234+
console.log(`${docQueue.dequeue()} -> ha sido impreso.`);
235+
console.log(`${docQueue.length} -> archivos faltantes.`);
236+
} else {
237+
console.log("No hay archivos.");
238+
}
239+
SelectAction();
240+
};
241+
242+
const DocPending = () => {
243+
const documentos = docQueue.toArray();
244+
console.log(documentos.length ? documentos.join(", ") : "No hay archivos.");
245+
SelectAction();
246+
};
247+
248+
const AddDoc = (doc) => {
249+
docQueue.enqueue(doc);
250+
console.log("Archivo agregado a la cola de impresión.");
251+
SelectAction();
252+
};
253+
254+
const SelectAction = () => {
255+
console.log("____________");
256+
rl.question("Acción: ", (option) => {
257+
switch (option) {
258+
case "p":
259+
PrintDoc();
260+
break;
261+
case "l":
262+
DocPending();
263+
break;
264+
case "x":
265+
rl.close;
266+
main();
267+
return
268+
default:
269+
AddDoc(option);
270+
}
271+
});
272+
};
273+
274+
console.log(mensajeImpresora);
275+
SelectAction();
276+
}
277+
278+
// ________________________________________________________
279+
const readline = require('readline');
280+
281+
const rl = readline.createInterface({
282+
input: process.stdin,
283+
output: process.stdout
284+
});
285+
286+
const MenuHome = `
287+
----------------------------------
288+
Usar: "1" para simulador de navegador.
289+
"2" para simulador de impresora.
290+
"Otra tecla" para salir.
291+
----------------------------------`;
292+
293+
function main() {
294+
console.log(MenuHome);
295+
rl.question("Seleccionar: ", (option) => {
296+
switch (option) {
297+
case "1":
298+
NavHistory();
299+
break;
300+
case "2":
301+
QueuePrinter();
302+
break;
303+
default:
304+
console.log("Adiós");
305+
rl.close();
306+
process.exit();
307+
}
308+
});
309+
}
310+
311+
main();

0 commit comments

Comments
 (0)