DEV Community

Discussion on: Pattern matching in JavaScript

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.