fromPredicate<L, R> function

Either<L, R> fromPredicate<L, R>(
  1. R value,
  2. bool predicate(
    1. R value
    ),
  3. L orElse(
    1. R value
    )
)

Create an Either from a function that returns a bool.

If the function returns true, then the returned Either will be a Right containing the given value.

If the function returns false, then the returned Either will be a Left containing the value returned from executing the orElse function.

expect(
  fromPredicate(2, (i) => i > 1, (_) => 'number too small'),
  equals(right(2)),
);
expect(
  fromPredicate(0, (i) => i > 1, (_) => 'number too small'),
  equals(left('number too small')),
);

Implementation

Either<L, R> fromPredicate<L, R>(
  R value,
  bool Function(R value) predicate,
  L Function(R value) orElse,
) =>
    predicate(value) ? right(value) : left(orElse(value));