Skip to content

Instantly share code, notes, and snippets.

@MPDADDY
Created August 28, 2023 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MPDADDY/bd9c28882b0c8b0427c619fc952de773 to your computer and use it in GitHub Desktop.
Save MPDADDY/bd9c28882b0c8b0427c619fc952de773 to your computer and use it in GitHub Desktop.
Assessing a piece of code if it is DRY
const pets = ['Cat', 'Dog', 'Bird', 'Fish', 'Frog', 'Hamster', 'Pig', 'Horse', 'Lion', 'Dragon'];
// Print all pets
console.log(pets[0]);
console.log(pets[1]);
console.log(pets[2]);
console.log(pets[3]);
...
//This code is not DRY because accessing the pets array and consolling each pet one by one is repeatetive activity and can be avoided by looping through the array.
//Same process can be acheived through this:
const myPets = pets.forEach(pet => console.log(pet));
/*This code also is not DRYand can be done in another way as DRY*/
.cat {
font-family: "Times New Roman", Times, serif;
font-size: 1rem;
color: #FFF;
}
.dog {
font-family: "Times New Roman", Times, serif;
font-size: 1rem;
color: #000;
}
.dragon {
font-family: "Times New Roman", Times, serif;
font-size: 1rem;
color: #009933;
}
/* Bellow is how the same code can be done following DRY concept*/
* {/* this styling applies to all element styled on this file */
font-family: "Times New Roman", Times, serif;
font-size: 1rem;
}
/*Now I give the individual style with no repeatition*/
.dragon {
color: #009933;
}
.dog {
color: #000;
}
.cat {
color: #FFF;
}
//This example here uses DRY because there is no repeatition of code.
//The function greet takes care of everything and only at the function call the message and the name are passed as arguments.
const greet = (message, name) => {
console.log(`${message}, ${name}!`)
}
greet('Hello', 'John');
greet('Hola', 'Antonio');
greet('Ciao', 'Luigi');
//aAlso the code bellow uses DRY because there is no repeatition.
.greetings {//This style applies to all greatings
font-family: Arial, sans-serif;
font-size: 1.5rem;
}
//While these last two styles applies to the individual languages
.greetings.english {
background-color: #000;
color: #FFF;
}
.greetings.spanish {
background-color: #FFF;
color: #000;
}
@MPDADDY
Copy link
Author

MPDADDY commented Aug 28, 2023

This gist shows how DRY could be implemented in both JavaScript and CSS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment