Apply list of functions to maybe value in Javascript

257 views Asked by At

I'm using ramda-fantasy for the monads. I have a string inside a maybe and a some functions that will perform regex matches on a string and return a Maybe String.

How do I map the maybe to apply all of the functions and concatenate the result?

I have

const fieldRetrievers = [ 
  getAddress,
  getName,
  getPhone, 
]

const text = Maybe.of("a text")

// I want to define
// List (String -> Maybe String) -> Maybe String -> Maybe String
function getInfo(retrievers, maybeText) {...}

How can I do that?

1

There are 1 answers

4
Bergi On

You're looking for composeK, the function composition over monadic structures ("kleisli arrows").

Basically, your resulting function is supposed to repeatedly chain onto the input:

text.chain(getAddress).chain(getName).chain(getPhone)

which you could implement using a reduce over your array of functions:

R.reduce((m, f) => m.chain(f), text, fieldRetrievers)

so you'd write

const getInfo = R.flip(R.reduce(R.flip(R.chain)))