Skip to content

Commit a5d0b44

Browse files
authored
Merge pull request #7062 from victor-Casta/[email protected]
#29 - JavaScript
2 parents 1798e67 + efbcfdd commit a5d0b44

File tree

3 files changed

+346
-0
lines changed

3 files changed

+346
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
const assert = require('assert')
2+
/*
3+
* EJERCICIO:
4+
* Crea una función que se encargue de sumar dos números y retornar
5+
* su resultado.
6+
* Crea un test, utilizando las herramientas de tu lenguaje, que sea
7+
* capaz de determinar si esa función se ejecuta correctamente.
8+
*/
9+
10+
function addition(a: number, b: number): number {
11+
return a + b
12+
}
13+
14+
try {
15+
assert.equal(addition(1, 2), 3)
16+
console.log(`Test 1: pasó. Resultado de la suma: ${addition(1, 2)}`)
17+
} catch (error) {
18+
console.error(`Test 1: falló. Error: ${error.message}`)
19+
}
20+
21+
/*
22+
* Crea un diccionario con las siguientes claves y valores:
23+
* "name": "Tu nombre"
24+
* "age": "Tu edad"
25+
* "birth_date": "Tu fecha de nacimiento"
26+
* "programming_languages": ["Listado de lenguajes de programación"]
27+
* Crea dos test:
28+
* - Un primero que determine que existen todos los campos.
29+
* - Un segundo que determine que los datos introducidos son correctos.
30+
*/
31+
32+
interface Person {
33+
name: string;
34+
age: number;
35+
birthDate: Date;
36+
programmingLanguages: string[];
37+
}
38+
39+
const person: Person = {
40+
name: 'Victor',
41+
age: 21,
42+
birthDate: new Date(2002, 11, 17),
43+
programmingLanguages: ['TypeScript', 'JavaScript', 'Python']
44+
};
45+
46+
function validateStructure(expected: Person, actual: Person): void {
47+
const expectedKeys = Object.keys(expected);
48+
const actualKeys = Object.keys(actual);
49+
assert.strictEqual(expectedKeys.length, actualKeys.length, 'Las estructuras no tienen el mismo número de claves.');
50+
expectedKeys.forEach(key => {
51+
assert.ok(actual.hasOwnProperty(key), `La propiedad "${key}" falta en el objeto real.`);
52+
});
53+
}
54+
55+
function validateValues(expected: Person, actual: Person): void {
56+
const expectedKeys = Object.keys(expected);
57+
expectedKeys.forEach(key => {
58+
assert.strictEqual(typeof actual[key], typeof expected[key], `El tipo de la propiedad "${key}" no coincide.`);
59+
});
60+
}
61+
62+
try {
63+
validateStructure({
64+
name: '',
65+
age: 0,
66+
birthDate: new Date(2002, 11, 17),
67+
programmingLanguages: ['']
68+
}, person);
69+
console.log('Test 1: pasó. La estructura es correcta.');
70+
} catch (error) {
71+
console.error('Test 1: falló. Error: ', error.message);
72+
}
73+
74+
try {
75+
validateValues({
76+
name: '',
77+
age: 0,
78+
birthDate: new Date(2002, 11, 17),
79+
programmingLanguages: ['']
80+
}, person);
81+
console.log('Test 2: pasó. Los tipos son correctos.');
82+
} catch (error) {
83+
console.error('Test 2: falló. Error: ', error.message);
84+
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
/*
2+
* EJERCICIO:
3+
* Explora el "Principio SOLID de Segregación de Interfaces (Interface Segregation Principle, ISP)"
4+
* y crea un ejemplo simple donde se muestre su funcionamiento de forma correcta e incorrecta.
5+
*/
6+
7+
// Forma incorrecta
8+
/*
9+
class Animal {
10+
fly() {
11+
console.log("Volar")
12+
}
13+
14+
swim() {
15+
console.log("Nadar")
16+
}
17+
18+
walk() {
19+
console.log("Caminar")
20+
}
21+
}
22+
23+
class Bird extends Animal {
24+
fly() {
25+
console.log("Volar")
26+
}
27+
}
28+
29+
class Fish extends Animal {
30+
swim() {
31+
console.log("Nadar")
32+
}
33+
}
34+
35+
class Dog extends Animal {
36+
walk() {
37+
console.log("Caminar")
38+
}
39+
fly() {
40+
throw new Error("No puede volar")
41+
}
42+
}
43+
44+
const bird = new Bird()
45+
bird.fly()
46+
47+
const fish = new Fish()
48+
fish.swim()
49+
50+
const dog = new Dog()
51+
dog.walk()
52+
53+
dog.fly()
54+
*/
55+
56+
// Forma correcta
57+
58+
class AnimalCanFly {
59+
fly() {
60+
console.log("Volar")
61+
}
62+
}
63+
64+
class AnimalCanSwim {
65+
swim() {
66+
console.log("Nadar")
67+
}
68+
}
69+
70+
class AnimalCanWalk {
71+
walk() {
72+
console.log("Caminar")
73+
}
74+
}
75+
76+
class Bird extends AnimalCanFly {
77+
fly() {
78+
console.log("Volar")
79+
}
80+
}
81+
82+
class Fish extends AnimalCanSwim {
83+
swim() {
84+
console.log("Nadar")
85+
}
86+
}
87+
88+
class Dog extends AnimalCanWalk {
89+
walk() {
90+
console.log("Caminar")
91+
}
92+
}
93+
94+
const bird = new Bird()
95+
const fish = new Fish()
96+
const dog = new Dog()
97+
98+
bird.fly()
99+
fish.swim()
100+
dog.walk()
101+
102+
/*
103+
* DIFICULTAD EXTRA (opcional):
104+
* Crea un gestor de impresoras.
105+
* Requisitos:
106+
* 1. Algunas impresoras sólo imprimen en blanco y negro.
107+
* 2. Otras sólo a color.
108+
* 3. Otras son multifunción, pueden imprimir, escanear y enviar fax.
109+
* Instrucciones:
110+
* 1. Implementa el sistema, con los diferentes tipos de impresoras y funciones.
111+
* 2. Aplica el ISP a la implementación.
112+
* 3. Desarrolla un código que compruebe que se cumple el principio.
113+
*/
114+
115+
class Printable {
116+
print(document) {
117+
console.log(`Printing ${document}`)
118+
}
119+
}
120+
121+
class Scannable {
122+
scan(document) {
123+
console.log(`Scanning ${document}`)
124+
}
125+
}
126+
127+
class Faxable {
128+
sendFax(document) {
129+
console.log(`Sending ${document}`)
130+
}
131+
}
132+
133+
class BlackAndWhitePrinter extends Printable {}
134+
class ColorPrinter extends Printable {}
135+
class MultifunctionalPrinter extends Printable {
136+
constructor() {
137+
super()
138+
this.scanner = new Scannable()
139+
this.fax = new Faxable()
140+
}
141+
142+
scan(document) {
143+
this.scanner.scan(document)
144+
}
145+
146+
sendFax(document) {
147+
this.fax.sendFax(document)
148+
}
149+
}
150+
151+
const bwPrinter = new BlackAndWhitePrinter()
152+
bwPrinter.print("Document1")
153+
154+
const colorPrinter = new ColorPrinter()
155+
colorPrinter.print("Document2")
156+
157+
const multiPrinter = new MultifunctionalPrinter()
158+
multiPrinter.print("Document3")
159+
multiPrinter.scan("Document3")
160+
multiPrinter.sendFax("Document3")
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* EJERCICIO:
3+
* Explora el "Principio SOLID de Inversión de Dependencias (Dependency Inversion
4+
* Principle, DIP)" y crea un ejemplo simple donde se muestre su funcionamiento
5+
* de forma correcta e incorrecta.
6+
*/
7+
8+
// Forma incorrecta
9+
10+
class Game {
11+
start() {
12+
return 'start'
13+
}
14+
}
15+
16+
class getTypeOfGame {
17+
constructor() {
18+
this.game = new Game()
19+
}
20+
}
21+
22+
// Forma correcta
23+
24+
class Game {
25+
start() {
26+
return 'start'
27+
}
28+
}
29+
30+
class GameType {
31+
constructor(typeOfGame) {
32+
this.typeOfGame = typeOfGame
33+
}
34+
35+
displayGame() {
36+
return this.typeOfGame.start()
37+
}
38+
}
39+
40+
const gameInstance = new Game()
41+
const gameType = new GameType(gameInstance)
42+
console.log(gameType.displayGame())
43+
44+
/*
45+
* DIFICULTAD EXTRA (opcional):
46+
* Crea un sistema de notificaciones.
47+
* Requisitos:
48+
* 1. El sistema puede enviar Email, PUSH y SMS (implementaciones específicas).
49+
* 2. El sistema de notificaciones no puede depender de las implementaciones específicas.
50+
* Instrucciones:
51+
* 1. Crea la interfaz o clase abstracta.
52+
* 2. Desarrolla las implementaciones específicas.
53+
* 3. Crea el sistema de notificaciones usando el DIP.
54+
* 4. Desarrolla un código que compruebe que se cumple el principio.
55+
*/
56+
57+
class Notification {
58+
send(message) {
59+
throw new Error('Método send() debe ser implementado')
60+
}
61+
}
62+
63+
class EmailNotification extends Notification {
64+
send(email) {
65+
console.log(`Sending Email: ${email}`)
66+
}
67+
}
68+
69+
class PushNotification extends Notification {
70+
send(push) {
71+
console.log(`Sending Push: ${push}`)
72+
}
73+
}
74+
75+
class SMSNotification extends Notification {
76+
send(sms) {
77+
console.log(`Sending SMS: ${sms}`)
78+
}
79+
}
80+
81+
class NotificationSystem {
82+
constructor(notificationService) {
83+
this.notificationService = notificationService
84+
}
85+
86+
sendNotification(message) {
87+
this.notificationService.send(message)
88+
}
89+
}
90+
91+
const emailService = new EmailNotification()
92+
const pushService = new PushNotification()
93+
const smsService = new SMSNotification()
94+
95+
const emailSystem = new NotificationSystem(emailService)
96+
emailSystem.sendNotification('Hello via Email')
97+
98+
const pushSystem = new NotificationSystem(pushService)
99+
pushSystem.sendNotification('Hello via Push')
100+
101+
const smsSystem = new NotificationSystem(smsService)
102+
smsSystem.sendNotification('Hello via SMS')

0 commit comments

Comments
 (0)