From 6a01d1630291234cb597a67605a8d75974481c77 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Sat, 9 Sep 2023 22:21:10 -0500 Subject: [PATCH 1/8] name num,function,booleanos --- src/clean-code/01-names.ts | 52 ++++++++++++++++++++++++++++++ src/clean-code/02-name-types.ts | 57 +++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 src/clean-code/01-names.ts create mode 100644 src/clean-code/02-name-types.ts diff --git a/src/clean-code/01-names.ts b/src/clean-code/01-names.ts new file mode 100644 index 00000000..39b3fbe9 --- /dev/null +++ b/src/clean-code/01-names.ts @@ -0,0 +1,52 @@ +(() => { + + // Ejemplo + // Archivos a evaluar - files to evaluate + const filesToEvaluate = [ + { id: 1, flagged: false }, + { id: 2, flagged: false }, + { id: 3, flagged: true }, + { id: 4, flagged: false }, + { id: 5, flagged: false }, + { id: 7, flagged: true }, + ]; + + // Archivos marcados para borrar - files to delete + const filesToDelete = filesToEvaluate.map( data => data.flagged ); + + + class AbstractUser { }; + class UserMixin { }; + class UserImplementation { }; + interface IUser { }; + + // Mejor + class User { }; + interface User { }; + + + // Todo: Tarea + + // día de hoy - today + const today = new Date(); + + // días transcurridos - elapsed time in days + const elapsedTimeIndays: number = 23; + + // número de archivos en un directorio - number of files in directory + const NumberOfFilesInDirectory = 33; + + // primer nombre - first name + const firsName = 'Fernando'; + + // primer apellido - last name + const LastName = 'Herrera'; + + // días desde la última modificación - days since modification + const dayLastModification = 12; + + // cantidad máxima de clases por estudiante - max classes per student + const maxClassesPerStudent = 6; + + +})(); diff --git a/src/clean-code/02-name-types.ts b/src/clean-code/02-name-types.ts new file mode 100644 index 00000000..b4764684 --- /dev/null +++ b/src/clean-code/02-name-types.ts @@ -0,0 +1,57 @@ +(() => { + + // arreglo de temperaturas celsius + const temperaturesCelsius = [33.6, 12.34]; + + // Dirección ip del servidor + const serverIp = '123.123.123.123'; + + // Listado de usuarios + const users = [{id: 1, email: 'fernando@google.com'},{ id: 2, email: 'juan@google.com' }, { id: 3, email: 'melissa@google.com' }]; + + // Listado de emails de los usuarios + const userEmails = users.map( users => users.email ); + + // Variables booleanas de un video juego + const canJump = false; + const canRun = true; + const haSItems = true; + const isLoading = false; + + // Otros ejercicios + // tiempo inicial + const initialTime = new Date().getTime(); + //.... + // 3 doritos después + //... + // Tiempo al final + const finalTime = new Date().getTime() - initialTime; + + + // Funciones + // Obtiene los libros + function getBooks() { + throw new Error('Function not implemented.'); + } + + // obtiene libros desde un URL + function getBooksByUrl( url: string) { + throw new Error('Function not implemented.'); + } + + // obtiene el área de un cuadrado basado en sus lados + function getSquareArea( side: number ) { + throw new Error('Function not implemented.'); + } + + // imprime el trabajo + function printJob() { + throw new Error('Function not implemented.'); + } + + + + + + +})(); From ed864e803063336acf1eb09601c03893f9b99534 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Sat, 9 Sep 2023 23:43:08 -0500 Subject: [PATCH 2/8] refact code --- src/clean-code/03-functions.ts | 45 ++++++++++++++++++++++++ src/clean-code/04-homework.ts | 64 ++++++++++++++++++++++++++++++++++ src/main.ts | 1 + 3 files changed, 110 insertions(+) create mode 100644 src/clean-code/03-functions.ts create mode 100644 src/clean-code/04-homework.ts diff --git a/src/clean-code/03-functions.ts b/src/clean-code/03-functions.ts new file mode 100644 index 00000000..b8e08686 --- /dev/null +++ b/src/clean-code/03-functions.ts @@ -0,0 +1,45 @@ +(() => { + + // función para obtener información de una película por Id + function getInformationMovie( movieId: string ) { + console.log({ movieId }); + } + + // función para obtener información de los actores de una película - Actors o Cast // id = movieId getMovieCast + function getMovieActors( movieId: string ) { + console.log({ movieId }); + } + + // funcion para obtener el bio del actor por el id + function getBioOfActor( ActorId: string ) { + console.log({ ActorId }); + } + + // Crear una película + interface props{ + cast:string[], + description: string, + rating: number, + title: string, + } + function createMovie({title, description, rating, cast}:props ) { + console.log({ title, description, rating, cast }); + } + + // Crea un nuevo actor + function createActor( fullName: string, birthDay: Date ): boolean { + + // tarea asincrona para verificar nombre + // .. + // .. + if ( fullName === 'fernando' ) return false; + + console.log('Crear actor',birthDay); + return true; + + } + + + + +})(); diff --git a/src/clean-code/04-homework.ts b/src/clean-code/04-homework.ts new file mode 100644 index 00000000..460e3168 --- /dev/null +++ b/src/clean-code/04-homework.ts @@ -0,0 +1,64 @@ +(() => { + + + // Resolver sin la triple condicional dentro del if + // includes? arrays? + function isRedFruit( fruit: string ): boolean { + const redFruits = ['ciruela','manzana','ciruela']; + return redFruits.includes(fruit)? true : false; + + } + + // Simplificar esta función + // switch? Object literal? validar posibles colores + type fruitColor='red'| 'yellow'|'purple'; + function getFruitsByColor( color: fruitColor ): string[] { + + const fruitByColor={ + red: ['manzana','fresa'], + yellow:['piña','banana'], + purple:['moras','uvas'], + + } + if(!Object.keys(fruitByColor).includes(color)) { + throw Error('the color must be: red, yellow, purple'); + } + + return fruitByColor[color]; + + + } + + // Simplificar esta función + let isFirstStepWorking = true; + let isSecondStepWorking = true; + let isThirdStepWorking = true; + let isFourthStepWorking = true; + + function workingSteps() { + + if( !isFirstStepWorking) return 'First step broken.'; + if(!isSecondStepWorking) return 'Second step broken.'; + if(!isThirdStepWorking) return 'Third step broken.'; + if(!isFourthStepWorking ) return 'Fourth step broken.'; + + return 'Working properly!'; + + } + + + // isRedFruit + console.log({ isRedFruit: isRedFruit('cereza'), fruit: 'cereza' }); // true + console.log({ isRedFruit: isRedFruit('piña'), fruit: 'piña' }); // true + + //getFruitsByColor + console.log({ redFruits: getFruitsByColor('red') }); // ['manzana', 'fresa'] + console.log({ yellowFruits: getFruitsByColor('yellow') }); // ['piña', 'banana'] + console.log({ purpleFruits: getFruitsByColor('purple') }); // ['moras', 'uvas'] + // console.log({ pinkFruits: getFruitsByColor('pink') }); // Error: the color must be: red, yellow, purple + + // workingSteps + console.log({ workingSteps: workingSteps() }); // Cambiar los valores de la línea 31 y esperar los resultados + + +})(); diff --git a/src/main.ts b/src/main.ts index 7da9c62a..f49891a9 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,5 @@ import './style.css' +import './clean-code/04-homework'; const app = document.querySelector('#app')! From b3fd8e7293e21e9928a92a0a931064a3384533b4 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Sun, 10 Sep 2023 00:29:36 -0500 Subject: [PATCH 3/8] implment method --- src/clean-code/03-functions.ts | 11 ++++++++++ src/clean-code/04-homework.ts | 2 +- src/clean-code/05-dry.ts | 38 ++++++++++++++++++++++++++++++++++ src/main.ts | 2 +- 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/clean-code/05-dry.ts diff --git a/src/clean-code/03-functions.ts b/src/clean-code/03-functions.ts index b8e08686..15dd440d 100644 --- a/src/clean-code/03-functions.ts +++ b/src/clean-code/03-functions.ts @@ -40,6 +40,17 @@ } + const getPayAmount = ({ isDead = false, isSeparated = true, isRetired = false }) => { + let result; + if ( isDead ) { + return 1500; + } + if ( isSeparated ) { + return 2500; + } + return isRetired?300:400; + +} })(); diff --git a/src/clean-code/04-homework.ts b/src/clean-code/04-homework.ts index 460e3168..236898c4 100644 --- a/src/clean-code/04-homework.ts +++ b/src/clean-code/04-homework.ts @@ -37,7 +37,7 @@ function workingSteps() { - if( !isFirstStepWorking) return 'First step broken.'; + if(!isFirstStepWorking) return 'First step broken.'; if(!isSecondStepWorking) return 'Second step broken.'; if(!isThirdStepWorking) return 'Third step broken.'; if(!isFourthStepWorking ) return 'Fourth step broken.'; diff --git a/src/clean-code/05-dry.ts b/src/clean-code/05-dry.ts new file mode 100644 index 00000000..0453f761 --- /dev/null +++ b/src/clean-code/05-dry.ts @@ -0,0 +1,38 @@ + +type size=''|'S'|'M'|'XL' +class Prouct{ + constructor( + public name:string='', + public price:number=0, + public size:size='', + ){} + + isProductReady():boolean{ + + for (const key in this) { + switch(typeof this[key]){ + case 'number': + if ((this[key])<=0)throw Error (`${key} is zero`); + break; + case 'number': + if ((this[key]).length<=0)throw Error (`${key} is empty`); + break; + } + + } + return true; + + } + tostring(){ + if(!this.isProductReady()){ + return ; + } + return `${this.name} (${this.price}) ${this.size}`; + } +}; + +(()=>{ + const bluePants=new Prouct('Blue Large',5,'M'); + console.log(bluePants.tostring()); + +})() \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index f49891a9..9619e459 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ import './style.css' -import './clean-code/04-homework'; +import './clean-code/05-dry'; const app = document.querySelector('#app')! From 6d9342ad023a1a437041b68c3913c5c7c4d69cdd Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Sun, 10 Sep 2023 20:20:11 -0500 Subject: [PATCH 4/8] unique response --- src/clean-code/05-dry.ts | 6 +-- src/clean-code/06-claes-a.ts | 65 ++++++++++++++++++++++++ src/clean-code/06-clases-b.ts | 95 +++++++++++++++++++++++++++++++++++ src/main.ts | 2 +- 4 files changed, 164 insertions(+), 4 deletions(-) create mode 100644 src/clean-code/06-claes-a.ts create mode 100644 src/clean-code/06-clases-b.ts diff --git a/src/clean-code/05-dry.ts b/src/clean-code/05-dry.ts index 0453f761..c5d359a6 100644 --- a/src/clean-code/05-dry.ts +++ b/src/clean-code/05-dry.ts @@ -14,9 +14,9 @@ class Prouct{ case 'number': if ((this[key])<=0)throw Error (`${key} is zero`); break; - case 'number': - if ((this[key]).length<=0)throw Error (`${key} is empty`); - break; + case 'string': + if ((this[key]).length<=0)throw Error (`${key} is empty`); + break; } } diff --git a/src/clean-code/06-claes-a.ts b/src/clean-code/06-claes-a.ts new file mode 100644 index 00000000..c8ba5802 --- /dev/null +++ b/src/clean-code/06-claes-a.ts @@ -0,0 +1,65 @@ +(() => { + + // No aplicando el principio de responsabilidad única + + type Gender = 'M'|'F'; + + class Person { + constructor( + public name: string, + public gender: Gender, + public birthdate: Date + ){} + } + + + class User extends Person { + + public lastAccess: Date; + + constructor( + public email: string, + public role: string, + name: string, + gender: Gender, + birthdate: Date, + ) { + super( name, gender, birthdate ); + this.lastAccess = new Date(); + } + + checkCredentials() { + return true; + } + } + + + class UserSettings extends User { + constructor( + public workingDirectory: string, + public lastOpenFolder : string, + email : string, + role : string, + name : string, + gender : Gender, + birthdate : Date + ) { + super(email, role, name, gender, birthdate ); + } + } + + + const userSettings = new UserSettings( + '/usr/home', + '/home', + 'fernando@google.com', + 'Admin', + 'Fernando', + 'M', + new Date('1985-10-21') + ); + + console.log({ userSettings }); + + +})(); \ No newline at end of file diff --git a/src/clean-code/06-clases-b.ts b/src/clean-code/06-clases-b.ts new file mode 100644 index 00000000..8a10f657 --- /dev/null +++ b/src/clean-code/06-clases-b.ts @@ -0,0 +1,95 @@ +(() => { + + // No aplicando el principio de responsabilidad única + + type Gender = 'M'|'F'; + + interface PersonProps{ + name: string; + gender: Gender; + birthdate: Date; + } + + class Person { + public birthDate: Date; + public gender: Gender; + public name: string; + constructor({ name, gender,birthdate}: PersonProps + ){ + this.name = name; + this.gender = gender; + this.birthDate = birthdate; + } + } + + + interface UserProps { + birthdate: Date; + email: string; + gender: Gender; + name: string; + role: string; + } + + + class User extends Person { + + public lastAccess: Date; + public email: string; + public role: string; + + constructor({role,email,name, gender,birthdate}:UserProps) { + super( {name, gender, birthdate}); + this.lastAccess = new Date(); + this.email = email; + this.role = role; + } + + checkCredentials() { + return true; + } + } + + interface UserSettings{ + birthdate : Date; + email : string; + gender : Gender; + lastOpenFolder : string; + name : string; + role : string; + workingDirectory: string; + } + + class UserSettings extends User { + public workingDirectory:string; + public lastOpenFolder:string; + constructor({ + workingDirectory, + lastOpenFolder , + email, + role, + name, + gender, + birthdate }:UserSettings + ) { + super({email, role, name, gender, birthdate} ); + this.lastOpenFolder=lastOpenFolder; + this.workingDirectory=workingDirectory; + } + } + + + const userSettings = new UserSettings({ + birthdate:new Date('1985-10-21'), + email:'fernando@google.com', + gender:'M', + lastOpenFolder:'/home', + name:'Carlos', + role:'Admin', + workingDirectory:'/usr/home', + }); + + console.log({ userSettings }); + + +})(); \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 9619e459..3eeb7138 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ import './style.css' -import './clean-code/05-dry'; +import './clean-code/06-clases-b'; const app = document.querySelector('#app')! From 0a8fb18f99aedfe3e4e2d2fa68d083d12a25ca07 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Sun, 10 Sep 2023 21:41:59 -0500 Subject: [PATCH 5/8] order argument --- src/clean-code/06-clases-c.ts | 104 ++++++++++++++++++++++++++++++++++ src/clean-code/07-tarea.ts | 56 ++++++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 src/clean-code/06-clases-c.ts create mode 100644 src/clean-code/07-tarea.ts diff --git a/src/clean-code/06-clases-c.ts b/src/clean-code/06-clases-c.ts new file mode 100644 index 00000000..167ed4f2 --- /dev/null +++ b/src/clean-code/06-clases-c.ts @@ -0,0 +1,104 @@ +(() => { + + // Aplicando responsabilidad unica + //preorizar la composion frente la herencia + + type Gender = 'M'|'F'; + + interface PersonProps{ + name: string; + gender: Gender; + birthdate: Date; + } + + class Person { + public birthDate: Date; + public gender: Gender; + public name: string; + constructor({ name, gender,birthdate}: PersonProps + ){ + this.name = name; + this.gender = gender; + this.birthDate = birthdate; + } + } + + + interface UserProps { + email: string; + role: string; + } + + + class User { + + public lastAccess: Date; + public email: string; + public role: string; + + constructor({role,email}:UserProps) { + this.lastAccess = new Date(); + this.email = email; + this.role = role; + } + + checkCredentials() { + return true; + } + } + + interface SettingsProps{ + lastOpenFolder : string; + workingDirectory: string; + } + + class Settings { + public workingDirectory:string; + public lastOpenFolder:string; + constructor({ + workingDirectory, + lastOpenFolder , + }:SettingsProps + ) { + this.lastOpenFolder=lastOpenFolder; + this.workingDirectory=workingDirectory; + } + } + + + interface UserSettingsProps{ + birthdate : Date; + email : string; + gender : Gender; + lastOpenFolder : string; + name : string; + role : string; + workingDirectory: string; + } + + class UserSettings{ + public person:Person; + public user:User; + public settings:Settings + + constructor({name,gender,birthdate,email,role,lastOpenFolder,workingDirectory}:UserSettingsProps){ + this.person=new Person({name,gender,birthdate}) + this.user=new User({email,role}) + this.settings= new Settings({lastOpenFolder,workingDirectory}) + } + } + + const userSettings = new UserSettings({ + birthdate:new Date('1985-10-21'), + email:'fernando@google.com', + gender:'M', + lastOpenFolder:'/home', + name:'Carlos', + role:'Admin', + workingDirectory:'/usr/home', + }); + + console.log({ userSettings }); + + +})(); \ No newline at end of file diff --git a/src/clean-code/07-tarea.ts b/src/clean-code/07-tarea.ts new file mode 100644 index 00000000..77bfcf17 --- /dev/null +++ b/src/clean-code/07-tarea.ts @@ -0,0 +1,56 @@ +(()=>{ + + //* Aplicar el principio de responsabilidad única + //* Priorizar la composición frente a la herencia + + type HtmlType = 'input'|'select'|'textarea'|'radio'; + + class HtmlElement { + constructor( + public id: string, + public type: HtmlType, + ) {} + } + + class InputAttributes { + constructor( + public value: string, + public placeholder: string, + + ) { + + } + } + + class InputEvents { + constructor( ) { + + } + + setFocus() {}; + getValue() {}; + isActive() {}; + removeValue() {}; + } + + + //? Idea para la nueva clase InputElement + + + class InputElement{ + public HtmlElement:HtmlElement; + public InputAttributes:InputAttributes; + public InputEvents:InputEvents + + constructor(value: string, placeholder: string, id: string ){ + this.HtmlElement=new HtmlElement(id, 'input') + this.InputAttributes=new InputAttributes(value,placeholder) + this.InputEvents=new InputEvents() + } + } + + const nameField = new InputElement('Fernando', 'Enter first name', 'txtName'); + + console.log({ nameField }); + +})() \ No newline at end of file From b4ddfb29aa80828c68bcd8e6cb58061bf9c7d0e6 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Tue, 12 Sep 2023 22:10:19 -0500 Subject: [PATCH 6/8] implement OPC --- package.json | 5 +- src/code-smell/01-singleton.js | 27 +++++++ src/code-smell/02-high-coupling.ts | 69 ++++++++++++++++++ src/code-smell/02-low-coupling.ts | 112 +++++++++++++++++++++++++++++ src/main.ts | 2 +- src/solid/-open-close-c..ts | 9 +++ src/solid/01-srp.ts | 86 ++++++++++++++++++++++ src/solid/02-open-close-a.ts | 20 ++++++ src/solid/02-open-close-b.ts | 43 +++++++++++ yarn.lock | 57 +++++++++++++++ 10 files changed, 428 insertions(+), 2 deletions(-) create mode 100644 src/code-smell/01-singleton.js create mode 100644 src/code-smell/02-high-coupling.ts create mode 100644 src/code-smell/02-low-coupling.ts create mode 100644 src/solid/-open-close-c..ts create mode 100644 src/solid/01-srp.ts create mode 100644 src/solid/02-open-close-a.ts create mode 100644 src/solid/02-open-close-b.ts diff --git a/package.json b/package.json index c7b4b1da..4383b681 100644 --- a/package.json +++ b/package.json @@ -10,5 +10,8 @@ "devDependencies": { "typescript": "^4.5.4", "vite": "^2.8.0" + }, + "dependencies": { + "axios": "^1.5.0" } -} \ No newline at end of file +} diff --git a/src/code-smell/01-singleton.js b/src/code-smell/01-singleton.js new file mode 100644 index 00000000..dbfe4589 --- /dev/null +++ b/src/code-smell/01-singleton.js @@ -0,0 +1,27 @@ +const Singleton = (function () { + + let instance; + + function createInstance() { + return new Object('I am the instance'); + } + + return { + getInstance() { + if (!instance) { + instance = createInstance(); + } + return instance; + } + }; +})(); + +function main() { + + const instance1 = Singleton.getInstance(); + const instance2 = Singleton.getInstance(); + + console.log('Misma instancia? ', (instance1 === instance2)); +} + +main(); \ No newline at end of file diff --git a/src/code-smell/02-high-coupling.ts b/src/code-smell/02-high-coupling.ts new file mode 100644 index 00000000..f5b236ba --- /dev/null +++ b/src/code-smell/02-high-coupling.ts @@ -0,0 +1,69 @@ +(()=>{ + // No aplicando el principio de responsabilidad única + type Gender = 'M'|'F'; + + // Alto Acoplamiento + + class Person { + constructor( + public name: string, + public gender: Gender, + public birthdate: Date, + ){} + } + + class User extends Person { + constructor( + public email: string, + public role: string, + private lastAccess: Date, + name: string, + gender: Gender, + birthdate: Date, + ){ + super(name, gender, birthdate); + this.lastAccess = new Date(); + } + + checkCredentials() { + return true; + } + } + + +class UserSettings extends User { + constructor( + public workingDirectory: string, + public lastFolderOpen: string, + email : string, + role : string, + name : string, + gender : Gender, + birthdate : Date, + ){ + super( + email, + role, + new Date(), + name, + gender, + birthdate + ) + } +} + + + + const userSettings = new UserSettings( + '/urs/home', + '/development', + 'fernando@google.com', + 'F', + 'Fernando', + 'M', + new Date('1985-10-21') + ); + + console.log({ userSettings, credentials: userSettings.checkCredentials() }); + +})() \ No newline at end of file diff --git a/src/code-smell/02-low-coupling.ts b/src/code-smell/02-low-coupling.ts new file mode 100644 index 00000000..373d78aa --- /dev/null +++ b/src/code-smell/02-low-coupling.ts @@ -0,0 +1,112 @@ +(()=>{ + // Aplicando el principio de responsabilidad única + // Prioriza la composición frente a la herencia + + type Gender = 'M'|'F'; + + interface PersonProps { + name : string; + gender : Gender; + birthdate: Date; + } + + class Person { + public name : string; + public gender : Gender; + public birthdate: Date; + + constructor({ name, gender, birthdate }: PersonProps ){ + this.name = name; + this.gender = gender; + this.birthdate = birthdate; + } + } + + + interface UserProps { + email : string; + role : string; + } + class User { + + public email : string; + public role : string; + private lastAccess : Date; + + constructor({ email, role }: UserProps ){ + this.lastAccess = new Date(); + this.email = email; + this.role = role; + } + + checkCredentials() { + return true; + } + } + + + interface SettingsProps { + lastFolderOpen : string; + workingDirectory: string; + } + + class Settings { + public workingDirectory: string; + public lastFolderOpen : string; + + constructor({ workingDirectory, lastFolderOpen }: SettingsProps ){ + this.workingDirectory = workingDirectory; + this.lastFolderOpen = lastFolderOpen; + } + } + + + // Nuevo User Settings + interface UserSettingsProps { + birthdate : Date; + email : string; + gender : Gender; + lastFolderOpen : string; + name : string; + role : string; + workingDirectory: string; + } + + class UserSettings { + // constructor( + // public person: Person, + // public user : User, + // public settings: Settings, + // ){} + public person : Person; + public user : User; + public settings: Settings; + + + + constructor({ + name, gender, birthdate, + email, role, + workingDirectory, lastFolderOpen, + }: UserSettingsProps) { + this.person = new Person({ name, gender, birthdate }); + this.user = new User({ email, role }); + this.settings = new Settings({ workingDirectory, lastFolderOpen }) + } + } + + + + const userSettings = new UserSettings({ + birthdate: new Date('1985-10-21'), + email: 'fernando@google.com', + gender: 'M', + lastFolderOpen: '/home', + name: 'Fernando', + role: 'Admin', + workingDirectory: '/usr/home' + }); + + console.log({ userSettings, credentials: userSettings.user.checkCredentials() }); + +})() \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 3eeb7138..8905d320 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ import './style.css' -import './clean-code/06-clases-b'; +import './solid/02-open-close-a'; const app = document.querySelector('#app')! diff --git a/src/solid/-open-close-c..ts b/src/solid/-open-close-c..ts new file mode 100644 index 00000000..4730a091 --- /dev/null +++ b/src/solid/-open-close-c..ts @@ -0,0 +1,9 @@ +import axios from "axios"; + + +export class HttpClinete{ + async get(url:string){ + const { data } = await axios.get(url); + return data; + } +} \ No newline at end of file diff --git a/src/solid/01-srp.ts b/src/solid/01-srp.ts new file mode 100644 index 00000000..9c8b3806 --- /dev/null +++ b/src/solid/01-srp.ts @@ -0,0 +1,86 @@ +(() => { + + interface Product { + id: number; + name: string; + } + + class ProductService{ + + + getProduct(id: number){ + console.log("Product",{id,name:'oleed Tv'}); + } + + saveProduct( product: Product ) { + // Realiza una petición para salvar en base de datos + console.log('Guardando en base de datos', product ); + } + } + + class Mailer{ + private masterEmail: string='CvelascoSaavedra@gmail.com'; + + sendEmail(email: string,template:'to-clientes'| 'to-admins'){ + console.log('Envio correo a los clientes',template); + } + } + + // Usualmente, esto es una clase para controlar la vista que es desplegada al usuario + // Recuerden que podemos tener muchas vistas que realicen este mismo trabajo. + class ProductBloc { + private productService:ProductService; + private mailer:Mailer; + + constructor(productService:ProductService, mailer:Mailer) { + this.productService = productService; + this.mailer = mailer; + } + + loadProduct( id: number ) { + this.productService.getProduct(id) + } + + + saveProduct( product: Product ) { + // Realiza una petición para salvar en base de datos + this.productService.saveProduct(product); + } + + notifyClients() { + this.mailer.sendEmail('Eduardo@gmail.com','to-clientes'); + } + + + } + + + class CardBloc{ + + private itemsInCart:object[]= []; + + onAddToCart( productId: number ) { + // Agregar al carrito de compras + console.log('Agregando al carrito ', productId ); + } + } + + const productService= new ProductService(); + const mailer= new Mailer(); + + const productBloc = new ProductBloc(productService,mailer); + const cardBloc= new CardBloc(); + + productBloc.loadProduct(10); + productBloc.saveProduct({ id: 10, name: 'OLED TV' }); + productBloc.notifyClients(); + cardBloc.onAddToCart(10); + + + + + + + + +})(); \ No newline at end of file diff --git a/src/solid/02-open-close-a.ts b/src/solid/02-open-close-a.ts new file mode 100644 index 00000000..7ae89b22 --- /dev/null +++ b/src/solid/02-open-close-a.ts @@ -0,0 +1,20 @@ +import { HttpClinete } from './-open-close-c.'; +import { PhotosService, PostService, TodoService } from './02-open-close-b'; + +(async () => { + + const httpClient = new HttpClinete(); + + const todoService = new TodoService(httpClient); + const postService = new PostService(httpClient); + const photosService = new PhotosService(httpClient); + + const todos = await todoService.getTodoItems(); + const posts = await postService.getPosts(); + const photos = await photosService.getPhotos(); + + + console.log({ todos, posts, photos }); + + +})(); \ No newline at end of file diff --git a/src/solid/02-open-close-b.ts b/src/solid/02-open-close-b.ts new file mode 100644 index 00000000..00c8fc18 --- /dev/null +++ b/src/solid/02-open-close-b.ts @@ -0,0 +1,43 @@ + +import { HttpClinete } from './-open-close-c.'; + + +export class TodoService { + + constructor (private http:HttpClinete ){; + } + + + async getTodoItems() { + + const { data } = await this.http.get('https://jsonplaceholder.typicode.com/todos/'); + return data; + } +} + + +export class PostService { + + constructor (private http:HttpClinete ){ + + } + + async getPosts() { + const { data } = await this.http.get('https://jsonplaceholder.typicode.com/posts'); + return data; + } +} + + +export class PhotosService { + + constructor (private http:HttpClinete ){ + + } + + async getPhotos() { + const { data } = await this.http.get('https://jsonplaceholder.typicode.com/photos'); + return data; + } + +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 4ba28aaa..4a80bbbf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,6 +2,32 @@ # yarn lockfile v1 +asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" + integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q== + +axios@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/axios/-/axios-1.5.0.tgz#f02e4af823e2e46a9768cfc74691fdd0517ea267" + integrity sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ== + dependencies: + follow-redirects "^1.15.0" + form-data "^4.0.0" + proxy-from-env "^1.1.0" + +combined-stream@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" + integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== + dependencies: + delayed-stream "~1.0.0" + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ== + esbuild-android-64@0.14.25: version "0.14.25" resolved "https://registry.yarnpkg.com/esbuild-android-64/-/esbuild-android-64-0.14.25.tgz#d532d38cb5fe0ae45167ce35f4bbc784c636be40" @@ -128,6 +154,20 @@ esbuild@^0.14.14: esbuild-windows-64 "0.14.25" esbuild-windows-arm64 "0.14.25" +follow-redirects@^1.15.0: + version "1.15.2" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13" + integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA== + +form-data@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" + integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.8" + mime-types "^2.1.12" + fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" @@ -152,6 +192,18 @@ is-core-module@^2.8.1: dependencies: has "^1.0.3" +mime-db@1.52.0: + version "1.52.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" + integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== + +mime-types@^2.1.12: + version "2.1.35" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" + integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== + dependencies: + mime-db "1.52.0" + nanoid@^3.3.1: version "3.3.1" resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.1.tgz#6347a18cac88af88f58af0b3594b723d5e99bb35" @@ -176,6 +228,11 @@ postcss@^8.4.6: picocolors "^1.0.0" source-map-js "^1.0.2" +proxy-from-env@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" + integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== + resolve@^1.22.0: version "1.22.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.0.tgz#5e0b8c67c15df57a89bdbabe603a002f21731198" From 2e35e3e7c625def3c059415ef43e4ea81872c171 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Tue, 12 Sep 2023 22:36:25 -0500 Subject: [PATCH 7/8] implement liskov --- src/solid/03-liskov-a.ts | 40 +++++++++++++++++++++++++++++++ src/solid/03-liskov-b.ts | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 src/solid/03-liskov-a.ts create mode 100644 src/solid/03-liskov-b.ts diff --git a/src/solid/03-liskov-a.ts b/src/solid/03-liskov-a.ts new file mode 100644 index 00000000..9ae2d2d0 --- /dev/null +++ b/src/solid/03-liskov-a.ts @@ -0,0 +1,40 @@ +import { Tesla, Audi, Toyota, Honda, Vehicle } from './03-liskov-b'; + + +(() => { + + const printCarSeats = ( cars: (Vehicle)[] ) => { + + for (const car of cars) { + + if( car instanceof Tesla ) { + console.log( 'Tesla', car.getVehicleOfSeats() ) + continue; + } + if( car instanceof Audi ) { + console.log( 'Audi', car.getVehicleOfSeats() ) + continue; + } + if( car instanceof Toyota ) { + console.log( 'Toyota', car.getVehicleOfSeats() ) + continue; + } + if( car instanceof Honda ) { + console.log( 'Honda', car.getVehicleOfSeats() ) + continue; + } + + } + } + + const cars = [ + new Tesla(7), + new Audi(2), + new Toyota(5), + new Honda(5), + ]; + + + printCarSeats( cars ); + +})(); \ No newline at end of file diff --git a/src/solid/03-liskov-b.ts b/src/solid/03-liskov-b.ts new file mode 100644 index 00000000..eb859d07 --- /dev/null +++ b/src/solid/03-liskov-b.ts @@ -0,0 +1,51 @@ +//sirven para para trabajar con herencias +export abstract class Vehicle{ + abstract getVehicleOfSeats(): number; +} + + + + +export class Tesla extends Vehicle { + + constructor( private numberOfSeats: number ) { + super(); + } + + getVehicleOfSeats() { + return this.numberOfSeats; + } +} + +export class Audi extends Vehicle { + + constructor( private numberOfSeats: number ) { + super(); + } + + getVehicleOfSeats() { + return this.numberOfSeats; + } +} + +export class Toyota extends Vehicle { + + constructor( private numberOfSeats: number ) { + super(); + } + + getVehicleOfSeats() { + return this.numberOfSeats; + } +} + +export class Honda extends Vehicle{ + + constructor( private numberOfSeats: number ) { + super(); + } + + getVehicleOfSeats() { + return this.numberOfSeats; + } +} From 5e29c1898a601117685388f9e0c2a44c5727c105 Mon Sep 17 00:00:00 2001 From: alberto8812 Date: Wed, 13 Sep 2023 06:47:42 -0500 Subject: [PATCH 8/8] dependency solid --- src/data/local-database.json | 32 ++++++++++++++++++++++++++++++++ src/solid/-segregation.ts | 29 +++++++++++++++++++++++++++++ src/solid/05-dependency-a.ts | 15 +++++++++++++++ src/solid/05-dependency-b.ts | 23 +++++++++++++++++++++++ src/solid/05-dependency-c.ts | 22 ++++++++++++++++++++++ 5 files changed, 121 insertions(+) create mode 100644 src/data/local-database.json create mode 100644 src/solid/-segregation.ts create mode 100644 src/solid/05-dependency-a.ts create mode 100644 src/solid/05-dependency-b.ts create mode 100644 src/solid/05-dependency-c.ts diff --git a/src/data/local-database.json b/src/data/local-database.json new file mode 100644 index 00000000..2701a0a6 --- /dev/null +++ b/src/data/local-database.json @@ -0,0 +1,32 @@ +[ + { + "userId": 1, + "id": 1, + "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", + "body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto" + }, + { + "userId": 1, + "id": 2, + "title": "qui est esse", + "body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla" + }, + { + "userId": 1, + "id": 3, + "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", + "body": "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut" + }, + { + "userId": 1, + "id": 4, + "title": "eum et est occaecati", + "body": "ullam et saepe reiciendis voluptatem adipisci sit amet autem assumenda provident rerum culpa quis hic commodi nesciunt rem tenetur doloremque ipsam iure quis sunt voluptatem rerum illo velit" + }, + { + "userId": 1, + "id": 5, + "title": "nesciunt quas odio", + "body": "repudiandae veniam quaerat sunt sed alias aut fugiat sit autem sed est voluptatem omnis possimus esse voluptatibus quis est aut tenetur dolor neque" + } + ] \ No newline at end of file diff --git a/src/solid/-segregation.ts b/src/solid/-segregation.ts new file mode 100644 index 00000000..94334b0a --- /dev/null +++ b/src/solid/-segregation.ts @@ -0,0 +1,29 @@ + +interface Bird{ + eat():void; + Ran():void + +} + +interface Flybird { + fly():void; +} + +class Tucan implements Bird,Flybird{ + + public fly(){} + public eat(){} + public Ran(){} + +} + +class Humminbird implements Bird,Flybird{ + public fly(){} + public eat(){} + public Ran(){} +} + +class Ostrich implements Bird { + public eat(){} + public Ran(){} +} \ No newline at end of file diff --git a/src/solid/05-dependency-a.ts b/src/solid/05-dependency-a.ts new file mode 100644 index 00000000..c1a1609f --- /dev/null +++ b/src/solid/05-dependency-a.ts @@ -0,0 +1,15 @@ + +import { PostService } from './05-dependency-b'; + + +// Main +(async () => { + + const postService = new PostService(); + + const posts = await postService.getPosts(); + + console.log({ posts }) + + +})(); \ No newline at end of file diff --git a/src/solid/05-dependency-b.ts b/src/solid/05-dependency-b.ts new file mode 100644 index 00000000..a4794d6c --- /dev/null +++ b/src/solid/05-dependency-b.ts @@ -0,0 +1,23 @@ +import { LocalDataBaseService } from "./05-dependency-c"; + +export interface Post { + body: string; + id: number; + title: string; + userId: number; +} + + +export class PostService { + + private posts: Post[] = []; + + constructor() {} + + async getPosts() { + const jsonDB = new LocalDataBaseService(); + this.posts = await jsonDB.getFakePosts(); + + return this.posts; + } +} \ No newline at end of file diff --git a/src/solid/05-dependency-c.ts b/src/solid/05-dependency-c.ts new file mode 100644 index 00000000..0a90ea76 --- /dev/null +++ b/src/solid/05-dependency-c.ts @@ -0,0 +1,22 @@ + +export class LocalDataBaseService { + + constructor() {} + + async getFakePosts() { + return [ + { + 'userId': 1, + 'id': 1, + 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', + 'body': 'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto' + }, + { + 'userId': 1, + 'id': 2, + 'title': 'qui est esse', + 'body': 'est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla' + }] + } + +} \ No newline at end of file