DEV Community

Discussion on: 5 Programming Patterns I Like

Collapse
 
geompse profile image
Geompse

Example with no object creation in the function:

// Object literal
const createContent = function(contentType){
   const contentTypes = createContent.contentTypes;
   const createType = contentTypes[contentType] || contentTypes.default;
   return createType(); // or new createType() if its a class constructor
}
createContent.contentTypes = {
  post: Post,
  video: Video,
  default: Unknown
};
Collapse
 
ecancino profile image
Eduardo Cancino • Edited

I love this solution, very simple;

I usually do this:

const  fromTypes = (types, def = null) => type => (types[type] || def)

const createContent = fromTypes({ post: Post, video: Video }, Unknown)

createContent('post')

Thread Thread
 
jaytailor45 profile image
Jay Tailor

This is how redux architecture works ;)