Skip to content

Commit e302733

Browse files
authored
Merge pull request mouredev#6832 from duendeintemporal/main
#17 - javascript
2 parents ba9f09a + 94337d4 commit e302733

File tree

3 files changed

+397
-0
lines changed

3 files changed

+397
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// #17 - ITERACIONES
2+
/*
3+
* EJERCICIO:
4+
* Utilizando tu lenguaje, emplea 3 mecanismos diferentes para imprimir
5+
* números del 1 al 10 mediante iteración.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Escribe el mayor número de mecanismos que posea tu lenguaje
9+
* para iterar valores. ¿Eres capaz de utilizar 5? ¿Y 10?
10+
*/
11+
12+
// short for console.log
13+
let log = console.log;
14+
15+
window.addEventListener('load', ()=>{
16+
const body = document.querySelector('body');
17+
const title = document.createElement('h1');
18+
19+
body.style.setProperty('background', '#000');
20+
body.style.setProperty('text-align', 'center');
21+
22+
title.textContent = 'Retosparaprogramadores #17.';
23+
title.style.setProperty('font-size', '3.5vmax');
24+
title.style.setProperty('color', '#fff');
25+
title.style.setProperty('line-height', '100vh');
26+
27+
body.appendChild(title);
28+
29+
setTimeout(()=>{
30+
alert('Retosparaprogramadores #17. Please open the Browser Developer Tools.');
31+
}, 2000);
32+
log( 'Retosparaprogramadores #17');
33+
});
34+
35+
for(let i = 1; i <= 10; i++){
36+
log(i);
37+
}
38+
39+
let count = 0;
40+
while(count < 10){
41+
count ++;
42+
log(count);
43+
}
44+
45+
// forEach method
46+
let nums = [1,2,3,4,5,6,7,8,9,10];
47+
nums.forEach(n=>log(n));
48+
49+
//Extra Dificulty Exercise
50+
51+
// do while
52+
let i = 0;
53+
do {
54+
console.log(i);
55+
i++;
56+
} while (i < 5);
57+
58+
//map method
59+
const arr = [1, 2, 3, 4, 5];
60+
const doubled = arr.map((value) => value * 2);
61+
log(doubled); // [2, 4, 6, 8, 10]
62+
63+
// filter method
64+
const arr1 = [1, 2, 3, 4, 5];
65+
const evenNumbers = arr1.filter((value) => value % 2 === 0);
66+
log(evenNumbers); // [2, 4]
67+
68+
// reduce method
69+
const arr2 = [1, 2, 3, 4, 5];
70+
const sum = arr2.reduce((total, current) => total + current, 0);
71+
log(sum); // 15
72+
73+
// some method
74+
const arr3 = [1, 2, 3, 4, 5];
75+
const hasEven = arr3.some((value) => value % 2 === 0);
76+
log(hasEven); // true
77+
78+
// every method
79+
const arr4 = [1, 2, 3, 4, 5];
80+
const allEven = arr4.every((value) => value % 2 === 0);
81+
log(allEven); // false
82+
83+
// For of...
84+
const arr5 = [1, 2, 3, 4, 5];
85+
for (const value of arr5) {
86+
log(value); // Logs: 1 2 3 4 5
87+
}
88+
89+
// Iteración con entries
90+
const arr6 = ['a', 'b', 'c'];
91+
for (const [index, value] of arr6.entries()) {
92+
log(index, value); // 0 'a' 1 'b' 2 'c'
93+
}
94+
95+
const obj1 = { a: 1, b: 2, c: 3 };
96+
for (const [key, value] of Object.entries(obj1)) {
97+
log(key, value); // a 1 b 2 c 3
98+
}
99+
100+
// Iteración con keys
101+
const arr7 = ['a', 'b', 'c'];
102+
for (const index of arr7.keys()) {
103+
log(index); // 0 1 2
104+
}
105+
106+
const obj2 = { a: 1, b: 2, c: 3 };
107+
for (const key of Object.keys(obj2)) {
108+
log(key); // a b c
109+
}
110+
111+
112+
// Iteración con values
113+
const arr8 = ['a', 'b', 'c'];
114+
for (const value of arr8.values()) {
115+
log(value); // a b c
116+
}
117+
118+
const obj3 = { a: 1, b: 2, c: 3 };
119+
for (const value of Object.values(obj3)) {
120+
log(value); // 1 2 3
121+
}
122+
123+
// For in...
124+
const obj = { a: 1, b: 2, c: 3 };
125+
for (const key in obj) {
126+
log(`${key}: ${obj[key]}`); // a: 1 b: 2 c: 3
127+
}
128+
129+
130+
131+
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
//#18 - CONJUNTOS
2+
/*
3+
* EJERCICIO:
4+
* Utilizando tu lenguaje crea un conjunto de datos y realiza las siguientes
5+
* operaciones (debes utilizar una estructura que las soporte):
6+
* - Añade un elemento al final.
7+
* - Añade un elemento al principio.
8+
* - Añade varios elementos en bloque al final.
9+
* - Añade varios elementos en bloque en una posición concreta.
10+
* - Elimina un elemento en una posición concreta.
11+
* - Actualiza el valor de un elemento en una posición concreta.
12+
* - Comprueba si un elemento está en un conjunto.
13+
* - Elimina todo el contenido del conjunto.
14+
*
15+
* DIFICULTAD EXTRA (opcional):
16+
* Muestra ejemplos de las siguientes operaciones con conjuntos:
17+
* - Unión.
18+
* - Intersección.
19+
* - Diferencia.
20+
* - Diferencia simétrica.
21+
*/
22+
23+
let log = console.log;
24+
25+
window.addEventListener('load', ()=>{
26+
const body = document.querySelector('body');
27+
const title = document.createElement('h1');
28+
29+
body.style.setProperty('background', '#000');
30+
body.style.setProperty('text-align', 'center');
31+
32+
title.textContent = 'Retosparaprogramadores #18.';
33+
title.style.setProperty('font-size', '3.5vmax');
34+
title.style.setProperty('color', '#fff');
35+
title.style.setProperty('line-height', '100vh');
36+
37+
body.appendChild(title);
38+
39+
setTimeout(()=>{
40+
alert('Retosparaprogramadores #18. Please open the Browser Developer Tools.');
41+
}, 2000);
42+
log( 'Retosparaprogramadores #18');
43+
});
44+
45+
46+
let arr = [1,2,3,4,5];
47+
log(arr)// [1,2,3,4,5]
48+
// Adds an element to the end.
49+
arr.push(6);
50+
log(arr); // [1,2,3,4,5,6]
51+
52+
// Adds an element to the beginning.
53+
arr.unshift(0);
54+
log(arr); // [0, 1, 2, 3, 4, 5, 6]
55+
// Adds multiple elements in bulk to the end.
56+
arr2 = [7,8,9,10];
57+
arr.push(...arr2);
58+
log(arr); //  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
59+
60+
// Adds multiple elements in bulk at a specific position.
61+
arr3 = [3.1, 3.2, 3.4]
62+
arr.splice(4,0, ...arr3);
63+
log(arr); // [0, 1, 2, 3, 3.1, 3.2, 3.4, 4, 5, 6, 7, 8, 9, 10]
64+
65+
// Removes an element at a specific position.
66+
arr.splice(6,1);
67+
log(arr); // [0, 1, 2, 3, 3.1, 3.2, 4, 5, 6, 7, 8, 9, 10]
68+
69+
// Updates the value of an element at a specific position.
70+
arr.splice(arr.length - 1, 1, 9.1);
71+
log(arr); // [0, 1, 2, 3, 3.1, 3.2, 4, 5, 6, 7, 8, 9, 9.1]
72+
73+
// Checks if an element is in a set.
74+
let nums = new Set();
75+
arr.forEach(n=>nums.add(n));
76+
log('Is 10 in nums: ', nums.has(10)) // false
77+
78+
// Removes all content from the set.
79+
nums.clear();
80+
log(nums); // {size: 0}
81+
82+
// EXTRA DIFFICULTY (optional):
83+
84+
// Union.
85+
let arr4 = [10, 11, 12, 13, 14];
86+
let union = new Set([...arr, ...arr4]);
87+
log('union: ', union); // {0, 1, 2, 3, 3.1, …}
88+
89+
// Intersection.
90+
let arr5 = [1,4,5,6,15,16,17,18,19];
91+
let intersection = new Set();
92+
arr5.forEach(n => {
93+
if (union.has(n)) {
94+
intersection.add(n);
95+
}});
96+
97+
log('Intersection:', [...intersection]); // [1, 4, 5, 6]
98+
99+
// Difference.
100+
let difference = new Set(arr);
101+
arr5.forEach(n => {
102+
if (difference.has(n)) {
103+
difference.delete(n);
104+
}});
105+
106+
log('Difference:', [...difference]); // [0, 2, 3, 3.1, 3.2, 7, 8, 9, 9.1]
107+
108+
// Symmetric difference.
109+
let symmetricDiff = new Set([...arr, ...arr5]);
110+
arr5.forEach(n => {
111+
if (union.has(n)) {
112+
symmetricDiff.delete(n);
113+
}
114+
});
115+
arr.forEach(n => {
116+
if (arr5.includes(n)) {
117+
symmetricDiff.delete(n);
118+
}});
119+
120+
log('Symmetric Difference:', [...symmetricDiff]); // [0, 2, 3, 3.1, 3.2, 7, 8, 9, 9.1, 15, 16, 17, 18, 19]
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
//#19 ENUMERACIONES
2+
//I use GPT as a reference for concepts
3+
/*
4+
* EJERCICIO:
5+
* Empleando tu lenguaje, explora la definición del tipo de dato
6+
* que sirva para definir enumeraciones (Enum).
7+
* Crea un Enum que represente los días de la semana del lunes
8+
* al domingo, en ese orden. Con ese enumerado, crea una operación
9+
* que muestre el nombre del día de la semana dependiendo del número entero
10+
* utilizado (del 1 al 7).
11+
*
12+
* DIFICULTAD EXTRA (opcional):
13+
* Crea un pequeño sistema de gestión del estado de pedidos.
14+
* Implementa una clase que defina un pedido con las siguientes características:
15+
* - El pedido tiene un identificador y un estado.
16+
* - El estado es un Enum con estos valores: PENDIENTE, ENVIADO, ENTREGADO y CANCELADO.
17+
* - Implementa las funciones que sirvan para modificar el estado:
18+
* - Pedido enviado
19+
* - Pedido cancelado
20+
* - Pedido entregado
21+
* (Establece una lógica, por ejemplo, no se puede entregar si no se ha enviado, etc...)
22+
* - Implementa una función para mostrar un texto descriptivo según el estado actual.
23+
* - Crea diferentes pedidos y muestra cómo se interactúa con ellos.
24+
*/
25+
26+
/* In JavaScript, Enums (short for "enumerations") are not a native feature of the language like in other programming languages (for example, TypeScript, C#, Java). However, you can simulate the behavior of enums using objects.
27+
28+
What are Enums?
29+
Enums are a way to define a set of named constants. They are used to represent a group of related values, making the code more readable and easier to maintain. For example, you might have an enum for the days of the week, the statuses of an order, or colors. */
30+
31+
window.addEventListener('load', ()=>{
32+
const body = document.querySelector('body');
33+
const title = document.createElement('h1');
34+
35+
body.style.setProperty('background', '#000');
36+
body.style.setProperty('text-align', 'center');
37+
38+
title.textContent = 'Retosparaprogramadores #19.';
39+
title.style.setProperty('font-size', '3.5vmax');
40+
title.style.setProperty('color', '#fff');
41+
title.style.setProperty('line-height', '100vh');
42+
43+
body.appendChild(title);
44+
45+
setTimeout(()=>{
46+
alert('Retosparaprogramadores #19. Please open the Browser Developer Tools.');
47+
}, 2000);
48+
log( 'Retosparaprogramadores #19');
49+
});
50+
51+
let log = console.log;
52+
53+
const DaysOfWeek = {
54+
MONDAY: 'Monday',
55+
TUESDAY: 'Tuesday',
56+
WEDNESDAY: 'Wednesday',
57+
THURSDAY: 'Thursday',
58+
FRIDAY: 'Friday',
59+
SATURDAY: 'Saturday',
60+
SUNDAY: 'Sunday'
61+
};
62+
63+
Object.freeze(DaysOfWeek);
64+
65+
const showDay = (day)=>{
66+
const w_days = Object.keys(DaysOfWeek);
67+
return (w_days[day - 1])? DaysOfWeek[w_days[day - 1]] : 'You enter a invalid day, try between 1 and 7';
68+
}
69+
70+
log(DaysOfWeek.MONDAY); // Monday
71+
log(showDay(3)) // Wednesday
72+
//Extra Dificulty Exercise
73+
74+
//Enum simulation
75+
const OrderStatus = {
76+
PENDING: 'Pending',
77+
SHIPPED: 'Shipped',
78+
DELIVERED: 'Delivered',
79+
CANCELED: 'Canceled'
80+
};
81+
82+
Object.freeze(OrderStatus);
83+
84+
class Order{
85+
constructor(id){
86+
this.id = id;
87+
this.state = OrderStatus.PENDING;
88+
}
89+
90+
setState(state){
91+
this.state = OrderStatus[state];
92+
}
93+
94+
getState(){
95+
return this.state;
96+
}
97+
98+
shipOrder(){
99+
if(this.state.toLowerCase() == OrderStatus.PENDING.toLowerCase()){
100+
log('The order is Shipped');
101+
this.setState('SHIPPED');
102+
}else {
103+
log(`Cannot ship. Current state: ${this.state}`);
104+
}
105+
}
106+
107+
deliverOrder(){
108+
if(this.state.toLowerCase() == OrderStatus.SHIPPED.toLowerCase()){
109+
log('The order is Delivered');
110+
this.setState('DELIVERED');
111+
}else{
112+
log(`Cannot deliver. The order state is: ${this.state}`);
113+
}
114+
}
115+
116+
cancelOrder(){
117+
if(this.state.toLowerCase() == OrderStatus.DELIVERED.toLowerCase()){
118+
log('Cannot cancel. The order has already been delivered.')
119+
}
120+
log('The order is Canceled');
121+
this.setState('CANCELED');
122+
}
123+
124+
describeOrder() {
125+
log(`Order ID: ${this.id}, Current State: ${this.state}`);
126+
}
127+
}
128+
129+
let order15 = new Order('001');
130+
let order16 = new Order('002');
131+
let order17 = new Order('003');
132+
133+
order16.shipOrder(); // The order is Shipped
134+
order15.deliverOrder(); // Cannot Deliver. The order state is: Pending
135+
order17.shipOrder(); // The order is Shipped
136+
137+
order16.deliverOrder(); // The order is Delivered
138+
order15.shipOrder(); // The order is Shipped
139+
order17.cancelOrder(); // The order is Canceled
140+
141+
log(order16.getState()); // Delivered
142+
log(order15.getState()); // Shipped
143+
log(order17.getState()); // Canceled
144+
145+
order16.shipOrder() // Cannot ship. Current state: Delivered
146+

0 commit comments

Comments
 (0)