Skip to content

Commit a015db5

Browse files
authored
Merge pull request #7000 from duendeintemporal/main
#28 - javascript
2 parents d020d9b + cd455da commit a015db5

File tree

3 files changed

+560
-0
lines changed

3 files changed

+560
-0
lines changed
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
//#28 - Principio SOLID de Sustitución de Liskov (Liskov Substitution Principle, LSP)
2+
/*
3+
* EJERCICIO:
4+
* Explora el "Principio SOLID de Sustitución de Liskov (Liskov Substitution Principle, LSP)"
5+
* y crea un ejemplo simple donde se muestre su funcionamiento
6+
* de forma correcta e incorrecta.
7+
*
8+
* DIFICULTAD EXTRA (opcional):
9+
* Crea una jerarquía de vehículos. Todos ellos deben poder acelerar y frenar, así como
10+
* cumplir el LSP.
11+
* Instrucciones:
12+
* 1. Crea la clase Vehículo.
13+
* 2. Añade tres subclases de Vehículo.
14+
* 3. Implementa las operaciones "acelerar" y "frenar" como corresponda.
15+
* 4. Desarrolla un código que compruebe que se cumple el LSP.
16+
*/
17+
18+
/* The Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented programming. This principle states that objects of a derived class should be able to replace objects of the base class without altering the correctness of the program. */
19+
20+
let log = console.log;
21+
22+
window.addEventListener('load', ()=>{
23+
const body = document.querySelector('body');
24+
const title = document.createElement('h1');
25+
26+
body.style.setProperty('background', '#000');
27+
body.style.setProperty('text-align', 'center');
28+
29+
title.textContent = 'Retosparaprogramadores #28.';
30+
title.style.setProperty('font-size', '3.5vmax');
31+
title.style.setProperty('color', '#fff');
32+
title.style.setProperty('line-height', '100vh');
33+
34+
body.appendChild(title);
35+
36+
setTimeout(()=>{
37+
alert('Retosparaprogramadores #28. Please open the Browser Developer Tools.');
38+
}, 2000);
39+
log( 'Retosparaprogramadores #28');
40+
});
41+
42+
43+
class Shape {
44+
area() {
45+
throw new Error("Method 'area' must be implemented");
46+
}
47+
}
48+
49+
class Rectangle extends Shape {
50+
constructor(width, height) {
51+
super();
52+
this.width = width;
53+
this.height = height;
54+
}
55+
56+
area() {
57+
return this.width * this.height;
58+
}
59+
}
60+
61+
class Square extends Shape {
62+
constructor(side) {
63+
super();
64+
this.side = side;
65+
}
66+
67+
area() {
68+
return this.side * this.side;
69+
}
70+
}
71+
72+
const calculateArea = (shape)=> {
73+
return shape.area();
74+
}
75+
76+
const rectangle = new Rectangle(83, 105);
77+
const square = new Square(40);
78+
79+
log(calculateArea(rectangle)); // 8715
80+
log(calculateArea(square)); // 1600
81+
82+
//Extra Dificulty Exercise
83+
84+
class Car {
85+
constructor(brand, model, maxSpeed, acceleration, deceleration) {
86+
this.brand = brand;
87+
this.model = model;
88+
this.maxSpeed = maxSpeed; // Maximum speed in km/h
89+
this.acceleration = acceleration; // Acceleration in km/h per second
90+
this.deceleration = deceleration; // Deceleration in km/h per second
91+
this.currentSpeed = 0; // Current speed in km/h
92+
}
93+
94+
accelerate(seconds) {
95+
const newSpeed = this.currentSpeed + (this.acceleration * seconds);
96+
this.currentSpeed = Math.min(newSpeed, this.maxSpeed);
97+
log(`${this.brand} ${this.model} accelerated to ${this.currentSpeed} km/h.`);
98+
}
99+
100+
brake(seconds) {
101+
const newSpeed = this.currentSpeed - (this.deceleration * seconds);
102+
this.currentSpeed = Math.max(newSpeed, 0);
103+
log(`${this.brand} ${this.model} braked to ${this.currentSpeed} km/h.`);
104+
}
105+
}
106+
107+
class SportsCar extends Car {
108+
constructor(brand, model) {
109+
super(brand, model, 300, 30, 20);
110+
}
111+
}
112+
113+
class FamilyCar extends Car {
114+
constructor(brand, model) {
115+
super(brand, model, 200, 15, 10);
116+
}
117+
}
118+
119+
function testCar(car) {
120+
car.accelerate(5);
121+
car.brake(2);
122+
}
123+
124+
125+
126+
const sportsCars = [
127+
{
128+
brand: "Ferrari",
129+
model: "488",
130+
maxSpeed: 330,
131+
acceleration: 30,
132+
deceleration: 20,
133+
},
134+
{
135+
brand: "Porsche",
136+
model: "911 Turbo S",
137+
maxSpeed: 320,
138+
acceleration: 28,
139+
deceleration: 18,
140+
},
141+
{
142+
brand: "Lamborghini",
143+
model: "Huracán",
144+
maxSpeed: 325,
145+
acceleration: 32,
146+
deceleration: 22,
147+
}
148+
];
149+
150+
const familyCars = [
151+
{
152+
brand: "Toyota",
153+
model: "Sienna",
154+
maxSpeed: 180,
155+
acceleration: 10,
156+
deceleration: 8,
157+
},
158+
{
159+
brand: "Honda",
160+
model: "Odyssey",
161+
maxSpeed: 175,
162+
acceleration: 9,
163+
deceleration: 7,
164+
},
165+
{
166+
brand: "Chrysler",
167+
model: "Pacifica",
168+
maxSpeed: 180,
169+
acceleration: 9,
170+
deceleration: 7,
171+
}
172+
];
173+
174+
175+
const sportsCar = new SportsCar(...Object.values(sportsCars[0]));
176+
const familyCar = new FamilyCar(...Object.values(familyCars[1]));
177+
178+
testCar(sportsCar); //Ferrari 488 accelerated to 150 km/h.
179+
// Ferrari 488 braked to 110 km/h.
180+
testCar(familyCar); // Honda Odyssey accelerated to 75 km/h.
181+
// Honda Odyssey braked to 55 km/h.
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
//#29 - Principio SOLID de Segregación de Interfaces (Interface Segregation Principle (ISP))
2+
/*
3+
* EJERCICIO:
4+
* Explora el "Principio SOLID de Segregación de Interfaces (Interface Segregation Principle, ISP)", y crea un ejemplo
5+
* simple donde se muestre su funcionamiento de forma correcta e incorrecta.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Crea un gestor de impresoras.
9+
* Requisitos:
10+
* 1. Algunas impresoras sólo imprimen en blanco y negro.
11+
* 2. Otras sólo a color.
12+
* 3. Otras son multifunción, pueden imprimir, escanear y enviar fax.
13+
* Instrucciones:
14+
* 1. Implementa el sistema, con los diferentes tipos de impresoras y funciones.
15+
* 2. Aplica el ISP a la implementación.
16+
* 3. Desarrolla un código que compruebe que se cumple el principio.
17+
*/
18+
//Bibliografy: The Web Development Glossary (Jens Oliver Meiert) (Z-Library)
19+
//GPT
20+
21+
/* Interface Segregation Principle
22+
The principle that no client should be forced to depend on methods it does
23+
not use. ISP splits interfaces that are very large into smaller and more
24+
specific ones so that clients will only have to know about the methods that
25+
are of interest to them. Such shrunken interfaces are also called role
26+
interfaces. ISP is intended to keep a system decoupled and thus easier to
27+
refactor, change, and redeploy. */
28+
29+
let log = console.log;
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 #29.';
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 #29. Please open the Browser Developer Tools.');
47+
}, 2000);
48+
log( 'Retosparaprogramadores #29');
49+
});
50+
51+
// Incorrect Example
52+
class PaymentService {
53+
processCreditCardPayment(amount) {}
54+
processPayPalPayment(amount) {}
55+
processBitcoinPayment(amount) {}
56+
}
57+
58+
class CreditCardPayment extends PaymentService {
59+
processCreditCardPayment(amount) {
60+
log(`Processing credit card payment of ${amount}`);
61+
}
62+
63+
processPayPalPayment(amount) {
64+
throw new Error("This payment method does not support PayPal payments");
65+
}
66+
67+
processBitcoinPayment(amount) {
68+
throw new Error("This payment method does not support Bitcoin payments");
69+
}
70+
}
71+
72+
class PayPalPayment extends PaymentService {
73+
processCreditCardPayment(amount) {
74+
throw new Error("This payment method does not support credit card payments");
75+
}
76+
77+
processPayPalPayment(amount) {
78+
log(`Processing PayPal payment of ${amount}`);
79+
}
80+
81+
processBitcoinPayment(amount) {
82+
throw new Error("This payment method does not support Bitcoin payments");
83+
}
84+
}
85+
86+
class BitcoinPayment extends PaymentService {
87+
processCreditCardPayment(amount) {
88+
throw new Error("This payment method does not support credit card payments");
89+
}
90+
91+
processPayPalPayment(amount) {
92+
throw new Error("This payment method does not support PayPal payments");
93+
}
94+
95+
processBitcoinPayment(amount) {
96+
log(`Processing Bitcoin payment of ${amount}`);
97+
}
98+
}
99+
100+
101+
const creditCardPayment = new CreditCardPayment();
102+
creditCardPayment.processCreditCardPayment(250); // Processing credit card payment of 250
103+
//creditCardPayment.processPayPalPayment(87); // This will throw an error
104+
//Error: This payment method does not support PayPal payments at CreditCardPayment.processPayPalPayment
105+
106+
// Correct Example
107+
class CreditCardPaymentService {
108+
processCreditCardPayment(amount) {
109+
log(`Processing credit card payment of ${amount}`);
110+
}
111+
}
112+
113+
class PayPalPaymentService {
114+
processPayPalPayment(amount) {
115+
log(`Processing PayPal payment of ${amount}`);
116+
}
117+
}
118+
119+
class BitcoinPaymentService {
120+
processBitcoinPayment(amount) {
121+
log(`Processing Bitcoin payment of ${amount}`);
122+
}
123+
}
124+
125+
126+
const creditCardPayment1 = new CreditCardPaymentService();
127+
creditCardPayment1.processCreditCardPayment(400); // Processing credit card payment of 400
128+
129+
const payPalPayment = new PayPalPaymentService();
130+
payPalPayment.processPayPalPayment(130); // Processing PayPal payment of 130
131+
132+
const bitcoinPayment = new BitcoinPaymentService();
133+
bitcoinPayment.processBitcoinPayment(0.020); // Processing Bitcoin payment of 0.02
134+
135+
136+
//Extra Dificulty Exercise
137+
138+
class BlackAndWhitePrinter{
139+
print(doc){
140+
log(`Printing: ${doc} in Black & White`);
141+
}
142+
}
143+
144+
class ColorPrinter{
145+
print(doc){
146+
log(`Printing: ${doc} in Color`);
147+
}
148+
}
149+
150+
class MultiFunctionPrinter{
151+
152+
printInBlackAndWhite(doc){
153+
log(`Printing: ${doc} in Black & White`);
154+
}
155+
156+
print(doc){
157+
log(`Printing: ${doc} in Color`);
158+
}
159+
160+
fax(doc){
161+
log(`Faxing: ${doc}`);
162+
}
163+
164+
scan(doc){
165+
log(`Scanning: ${doc}`);
166+
}
167+
}
168+
169+
let book = 'vuelointemporal.odt';
170+
171+
const bw_printer = new BlackAndWhitePrinter();
172+
bw_printer.print(book); // Printing: vuelointemporal.odt in Black & White
173+
174+
const c_printer = new ColorPrinter();
175+
c_printer.print(book); // vuelointemporal.odt in Color
176+
177+
const m_printer = new MultiFunctionPrinter();
178+
m_printer.printInBlackAndWhite(book); // vuelointemporal.odt in Black & White
179+
m_printer.print(book); // Printing: vuelointemporal.odt in Color
180+
m_printer.fax(book); // Faxing: vuelointemporal.odt
181+
m_printer.scan(book); // Scanning: vuelointemporal.odt

0 commit comments

Comments
 (0)