Created
February 27, 2023 10:55
-
-
Save preciousuwhubetine/4630e6b18739564573ba19cbf1a344f8 to your computer and use it in GitHub Desktop.
Is it DRY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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