Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Carlos #12

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"devDependencies": {
"typescript": "^4.5.4",
"vite": "^2.8.0"
},
"dependencies": {
"axios": "^1.5.0"
}
}
}
52 changes: 52 additions & 0 deletions src/clean-code/01-names.ts
Original file line number Diff line number Diff line change
@@ -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;


})();
57 changes: 57 additions & 0 deletions src/clean-code/02-name-types.ts
Original file line number Diff line number Diff line change
@@ -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: '[email protected]'},{ id: 2, email: '[email protected]' }, { id: 3, email: '[email protected]' }];

// 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.');
}






})();
56 changes: 56 additions & 0 deletions src/clean-code/03-functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
(() => {

// 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;

}


const getPayAmount = ({ isDead = false, isSeparated = true, isRetired = false }) => {
let result;
if ( isDead ) {
return 1500;
}
if ( isSeparated ) {
return 2500;
}
return isRetired?300:400;

}


})();
64 changes: 64 additions & 0 deletions src/clean-code/04-homework.ts
Original file line number Diff line number Diff line change
@@ -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


})();
38 changes: 38 additions & 0 deletions src/clean-code/05-dry.ts
Original file line number Diff line number Diff line change
@@ -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 ((<number>this[key])<=0)throw Error (`${key} is zero`);
break;
case 'string':
if ((<string>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());

})()
65 changes: 65 additions & 0 deletions src/clean-code/06-claes-a.ts
Original file line number Diff line number Diff line change
@@ -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',
'[email protected]',
'Admin',
'Fernando',
'M',
new Date('1985-10-21')
);

console.log({ userSettings });


})();
Loading