Last active
December 27, 2018 22:35
-
-
Save jlem/20c9788a80e566c7246b544c43807fa7 to your computer and use it in GitHub Desktop.
Normalize inputs to dry up and flatten code structure
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
// Now the data you'll be working with will ALWAYS be an array, so you can plan for that. | |
// You still needed the conditional (a ternary in this case), but you've pushed it to the top of your code | |
// allowing all subsequent code to work with it in a more uniform way. | |
const normalizedData = Array.isArray(data) ? data : [data]; | |
const transformedData = normalizedData.map(myTransformerFunction); |
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
let transformedData; | |
if (Array.isArray(data)) { | |
transformedData = data.map(myTransformerFunction); | |
} | |
else { | |
transformedData = [data].map(myTransformerFunction); | |
} | |
// Note the nearly identical work being done in each conditional branch? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment