DEV Community

Discussion on: 5 Programming Patterns I Like

Collapse
 
nepeckman profile image
nepeckman

Personally, my favorite way to do JavaScript switches is to isolate them to their own function. If you're doing a simple dispatch, a function is already an appropriate abstraction, and return gives you the ability to avoid the break mess.

// Object literal
function createContent(contentType){
   const contentTypes = {
     post: Post,
     video: Video,
     default: Unknown
   };
   const createType = contentTypes[contentType] || contentTypes['default'];
   return createType(); // or new createType() if its a class constructor
}

// Switch
function createContent(contentType){
  switch(contentType){
    case "post": return Post() // or new Post() if its a class constructor
    case "video": return Video()
    default: return Unknown()
  }
}

Utilizing the switch statement also dodges the biggest drawback of the object literal: the location of the object. If you put the object literal in your dispatch function, you're creating the object every time you run the function. If you create the object once outside of the function, now your dispatch logic is in a different place than the actual dispatch call.

I wish JavaScript had a built in pattern matching construct, but a well used switch statement isn't all that bad.

Collapse
 
kleene1 profile image
kleene1

Cool post ! :)

Collapse
 
evanplaice profile image
Evan Plaice

Why not wrap the whole thing in one function. Use it as a closure to store the type data then return the switch function to access it?

Collapse
 
thejohnstew profile image
John Stewart

I like that switch versus the one I wrote. :D

I recently discovered pattern matching via Scala and enjoyed using it!

Collapse
 
keevcodes profile image
Andrew McKeever

Love seeing these posts! I just recently used a switch in my code and didn't like the overall bulk the switch created. Nice ideas on how to clean it up!

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 ;)