dimanche 17 juin 2018

What is the name of this pattern for checking multiple conditions?

I don't like if-statements and I am in love with functional programming. If-statements can get quite confusing and also you can't dynamically create them (at least not in Javascript).

Instead of hard-coding a list of if-statements I like to create an array of conditions that Ia can then reduce to the result. The advantages I see:

  • You can dynamically create lists of conditions (conditions.push())
  • I think it reads more easily then an if or switch statement, without any of the downsides
  • You can use the same list of conditions to either find the first condition that is met or all conditions that are met, or reverse it and find the first one that is not met or all that are not met - you get the point

My question is: Is there a name for such a pattern?

Bonus question: Is there anything I am missing why this could be a stupid idea?


Examples

What you would do with if statements (simplified example):

function ( valueA, valueB ) {
  if ( !valueA ) {
    return 'Value A is undefined';
  } else if ( !valueB ) {
    return 'Value B is undefined';
  } else if ( valueA + valueB === 0 ) {
    return 'Both values cancel each other out'
  }

  return null
}

I like to do something like this:

const conditionList = [
  {
    condition: ( a ) => !a,
    returnValue: 'Value A is undefined'
  },
  {
    condition: ( a, b ) => !b,
    returnValue: 'Value B is undefined'
  },
  {
    condition: ( a, b ) => a + b === 0,
    returnValue: 'Both values cancel each other out'
  }
]

const conditionListReducer = 
  conditionListReducerFactory( conditionList )

const result = conditionListReducer( 1, -1 ) // Both values cancel each other out

The condition list reducer factory looks something like this:

const conditionListReducerFactory = 
  conditionList => 
    ( ...args ) => {
      const metCondition = conditionList
        .find( ( { condition } ) => condition( ...args ) )

      return metCondition ?
        metCondition.returnValue
        : null
     }

Aucun commentaire:

Enregistrer un commentaire