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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With