maybify
v0.0.1
Published
`maybify` returns an object proxy that wraps existing methods of the object in conditional `maybe*` wrappers.
Downloads
4
Readme
maybify
returns an object proxy that wraps existing methods of the object in conditional maybe*
wrappers.
This can be useful when using a Builder design pattern with optional flags.
For example, the following builder:
let pizzaBuilder = new PizzaBuilder()
.addDough()
.addSauce();
if ( addCheese ) {
pizzaBuilder = pizzaBuilder.addCheese(10);
}
if ( addPepperoni ) {
pizzaBuilder = pizzaBuilder.addPepperoni(5);
}
if ( addBacon ) {
pizzaBuilder = pizzaBuilder.addBacon();
}
const pizza = pizzaBuilder.bake();
can be reimplemented with maybify
:
const pizza = maybify(new PizzaBuilder())
.addDough()
.addSauce()
.maybeAddCheese(addCheese, 10) // addCheese is passed as a flag
.maybeAddPepperoni(() => addPepperoni, 5) // addPepperoni is passed as a predicate
.maybeAddBacon(() => addBacon)
.bake();
Another example is a RethinkDB ReQL query expression builder:
return maybify(r.table('users'))
.filter({ status: 'active' })
.maybeSlice(() => sliced, begin, end)
.maybeOrderBy(() => ordered, 'name')
.run(connection);