DEV Community

Discussion on: Pattern matching in JavaScript

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.