Undistraction
Undistraction

Reputation: 43370

Handling User Configuration In Functional Programming

I have a series of (pure) functions responsible for expanding tokens held in an object graph.

I won't go into the details as they aren't important, but they are something like:

expandData => expandDataNodes => expandDataNode => expandDataNodeItem

I have everything working fine, but I now have a new requirement which means I now need user defined configuration to be available in expandDataNodeItem. Obviously in the OO world this is a trivial problem to solve just make the config available on the DataExpander class via a getter and pull it out when needed, but I'm interested in the options for handling this situation when using a functional paradigm.

I know I can add a param to each of these functions and pass down either the option or a function for accessing the option, but this results in lots of functions which have no interest in the option getting it added to their signatures which feels like it really muddies things.

The best option I can think of at the moment is to wrap all these functions in another function and use closure to make the options available to all functions within, but is there a better way?

Upvotes: 2

Views: 709

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

With these few details I would try another approach: you may refactor your code so the functionality that requires some configuration may come already injected in a partially-applied function. That is, your current function should be a high-order function.

Check the following sample on which I demonstrate that approach:

const f = ( { config1, configN } ) => x => config1 + x
const g = f => x => f ( x )

const settings = {
  config1: 1
}

// _f would be the function that you would provide
// when you need to do certain operation based on 
// who knows what configuration
const _f = f ( settings )
const y = g ( _f ) ( 2 )

console.log( y )

Upvotes: 2

Related Questions