lundi 10 décembre 2018

What functional-pattern is this? If any?

I find myself over and over again, writing code like this, and is thinking. There must be a known pattern for this, but plowing through documentation of different functional libs like Ramda. I can't quite find a match. What should I use?

var arrayOfPersons = [{ firstName: 'Jesper', lastName: 'Jensen', income: 120000, member: true }/* .... a hole lot of persons */];

function createPredicateBuilder(config) {

  return {

    build() {
      var fnPredicate = (p) => true;

      if (typeof config.minIncome == 'number') {
        fnPredicate = (p) => fnPredicate(p) && config.minIncome <= p.income;
      }
      if (typeof config.member == 'boolean') {
        fnPredicate = (p) => fnPredicate(p) && config.member === p.member;
      }
      // .. continue to support more predicateparts.
    },

    map(newConfig) {
      return createPredicateBuilder({ ...config, ...newConfig });
    }
  };
}

var predicateBuilder = createPredicateBuilder({});

// We collect predicates
predicateBuilder = predicateBuilder.map({ minIncome: 200000 });
// ...
predicateBuilder = predicateBuilder.map({ member: false });

// Now we want to query...
console.log(arrayOfPersons.filter(predicateBuilder.build()));

I create a builder instance, and calls to map, creates a new instance returning in an object with build/map methods. The state is captured in the functions scope. Sometime in the future, I want to get my collected function (or result).

I think this is FP, but what is this pattern, and is there any libs that makes it easyer?

Is my oop-inspired naming of things (builder/build) blinding me?

Aucun commentaire:

Enregistrer un commentaire