Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Variadic Version of either (R.either)?

I have a need for a variadic version of R.either. After doing some searching around the web, I have not found a solution. R.anyPass would work but it returns a Boolean instead of the original value. Is there already a solution that I have overlooked? If not, what would be the most optimal way to write a variadic either utility function?

An example:

const test = variadicEither(R.multiply(0), R.add(-1), R.add(1), R.add(2))
test(1) // => 2 
like image 482
webstermath Avatar asked Jul 01 '19 18:07

webstermath


1 Answers

You could use a combination of reduce + reduced:

const z = (...fns) => x => reduce((res, fn) => res ? reduced(res) : fn(x), false, fns);

console.log(
  z(always(0), always(10), always(2))(11),
  z(always(0), always(''), always(15), always(2))(11),
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {reduce, reduced, always} = R;</script>

(previous attempt)

I would do something like this:

const z = unapply(curry((fns, x) => find(applyTo(x), fns)(x)));

console.log(

  z(always(0), always(15), always(2))(10),
  z(always(0), always(''), always(NaN), always(30), always(2))(10),

);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {unapply, curry, find, applyTo, always} = R;</script>

There are three main caveats to this though!

  1. You have to call z in two "passes", i.e. z(...functions)(x)
  2. Although it should be easy to add, I didn't care about the case where no function "matches"
  3. Perhaps not a big deal but worth noting: a matching predicate will be executed twice
like image 174
customcommander Avatar answered Oct 06 '22 00:10

customcommander