Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operations in function composition

How do I stop or branch a composition based on some logical condition?

For example. Suppose I have the following code:

compose(
  operation4
  operation3,
  operation2,
  operation1
)(myStuff);

Or even something like

myStuff
 .map(operation1)
 .map(operation2)
 .map(operation3)
 .map(operation4)

And I only want operations 3 and 4 to be executed if myStuff fulfils some condition.

How do I implement that (specially in JavaScript)?

Do I have to create two smaller compositions and have a separate if statement or is there a way to have the condition within the composition?

Could Monads solve my problem? If so, how?

like image 479
Marcelo Lazaroni Avatar asked Aug 30 '16 10:08

Marcelo Lazaroni


1 Answers

A simple but practical approach is to have a function like when(cond, f) which executes f (which can in turn be a composition) only if cond(x) returns true:

_do = (...fns) => x => fns.reduce((r, f) => f(r), x);
_when = (cond, f) => x => cond(x) ? f(x) : x;


// example

add3 = x => x + 3;
add5 = x => x + 5;
add9 = x => x + 9;


pipe = _do(
    add3,
    add5,
    _when(x => x > 20, _do(add9))
)


console.log(pipe(30))
console.log(pipe(1))
like image 177
georg Avatar answered Sep 27 '22 17:09

georg