seasonedcc / composable-functions

Types and functions to make composition easy and safe
MIT License
652 stars 13 forks source link

Branch combinator #82

Closed gustavoguichard closed 1 year ago

gustavoguichard commented 1 year ago

Proposal

We often see people asking for some kind of conditional combinator to help doing code branching in compositions.

This is my proposal to solve that, I'm still not sure about the function name but I like how it enables more complex code branching than first and, what I also like about this approach, you can add some information on the output of a that will help on the condition but will be thrown away right after, e.g:

import { branch, makeDomainFunction as mDF } from 'domain-functions'
const a = mDF(z.number)(n => ({ n, next: 'multiply' }))
const b = mDF(z.object({ n: z.number() }))(({ n }) => n + 1)
const c = mDF(z.object({ n: z.number() }))(({ n }) => n * 2)

const df = branch(a, ({ next }) => next === "multiply" ? c : b)

If the condition function (the second argument) throws it will result in a normal DF error ({ success: false, errors: [...] }).

If this PR is welcome I'll make sure to write some docs before merging it ;)

diogob commented 1 year ago

I really like the approach of having a resolver function. It will also allow for true branching since first if actually a parallel application. Let's add some docs and get this merged :man_singer: