DEV Community

Cover image for Pattern matching in JavaScript

Pattern matching in JavaScript

Massimo Artizzu on January 14, 2020

Pattern matching is a pretty common action performed on entities in order to check if they follow some pattern or not. For example, an object repr...
Collapse
 
savagepixie profile image
SavagePixie

Then real problem here is that it's good just for static values, as the following approach would execute all the expressions:

You could do something like this:

const ACTIONS = {
  save: action => saveThing(action.payload),
  load: action => loadThing(action.payload.id),
  delete: action => deleteThing(action.payload.id)
}
ACTIONS[action.type](action)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maxart2501 profile image
Massimo Artizzu

Yes indeed! The point is that we have to be careful about this technique because those aren't branches and are eagerly executed.

Wrapping it in a function solves the problem but it's not something we do with if statements, for example 😄

Collapse
 
pclundaahl profile image
Patrick Charles-Lundaahl

Not sure about performance, but you can swap the immediate invocation for a bind. Eg:

const ACTIONS = {
  save: action => saveThing.bind(this, action.payload),
  load: action => loadThing.bind(this, action.payload.id),
  delete: action => deleteThing.bind(this, action.payload.id)
}
ACTIONS[action.type]()

This way none of your functions get invoked except the one that you explicitly match.

You would probably want to throw a guard condition in there so you don't try to invoke undefined, but this would be my standard approach for anything that needs a dynamic list of functions that have external dependencies.

Collapse
 
pclundaahl profile image
Patrick Charles-Lundaahl

I'd wager it would be pretty straightforward to build a library to do this. I built something similar to verify json against user-defined schemas. You could extend that idea to check conditions or pass arguments into a callback on success.

Collapse
 
maxart2501 profile image
Massimo Artizzu

There's something about in Lodash:
lodash.com/docs/4.17.11#cond

Collapse
 
pclundaahl profile image
Patrick Charles-Lundaahl

Neat! I've never actually used lodash, but it looks like it has some really nice utility methods.

Collapse
 
victorioberra profile image
Victorio Berra

Coming soon to babel: github.com/babel/babel/pull/9318

Collapse
 
maxart2501 profile image
Massimo Artizzu

Oh I hope so!

Alas, it won't be for production projects for a while, but a working Babel plugin is important to make things move forward.