Skip to content

Instantly share code, notes, and snippets.

@preciousbetine
Created February 27, 2023 10:55
Show Gist options
  • Save preciousbetine/4630e6b18739564573ba19cbf1a344f8 to your computer and use it in GitHub Desktop.
Save preciousbetine/4630e6b18739564573ba19cbf1a344f8 to your computer and use it in GitHub Desktop.
Is it 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]);
// Is it DRY?
// No. The code above is not DRY because there are repitions
// It can be made DRY by doing the following
const pets = ['Cat', 'Dog', 'Bird', 'Fish', 'Frog', 'Hamster', 'Pig', 'Horse', 'Lion', 'Dragon'];
pets.forEach((pet) => {
console.log(pet);
});
const greet = (message, name) => {
console.log(`${message}, ${name}!`)
}
greet('Hello', 'John');
greet('Hola', 'Antonio');
greet('Ciao', 'Luigi')
// This code is DRY but it can be made 'DRYer' by using an array of objects and a forEach loop a follows:
const greet = (message, name) => {
console.log(`${message}, ${name}!`)
}
const greetings = [
{ message: 'Hello', name: 'John' },
{ message: 'Hola', name: 'Antonio' },
{ message: 'Ciao', name: 'Luigi' },
];
greetings.forEach((greeting) => {
const {message, name} = greeting;
greet(message, name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment