Skip to content

Instantly share code, notes, and snippets.

@jlem
Last active December 27, 2018 22:35
Show Gist options
  • Save jlem/20c9788a80e566c7246b544c43807fa7 to your computer and use it in GitHub Desktop.
Save jlem/20c9788a80e566c7246b544c43807fa7 to your computer and use it in GitHub Desktop.
Normalize inputs to dry up and flatten code structure
// 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);
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