Skip to content

Commit

Permalink
Add [Either,Option].orNull. Closes spebbe#86.
Browse files Browse the repository at this point in the history
  • Loading branch information
cranst0n committed Jan 14, 2022
1 parent e46686f commit ec80b9f
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/src/either.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ abstract class Either<L, R> implements TraversableMonadOps<Either<L, dynamic>, R

Either<L, R> orElse(Either<L, R> other()) => fold((_) => other(), (_) => this);
R getOrElse(R dflt()) => fold((_) => dflt(), id);
R? get orNull => fold((_) => null, id);
R operator |(R dflt) => getOrElse(() => dflt);
Either<L2, R> leftMap<L2>(L2 f(L l)) => fold((L l) => left(f(l)), right);
Option<R> toOption() => fold((_) => none(), some);
Expand Down
1 change: 1 addition & 0 deletions lib/src/option.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ abstract class Option<A> implements TraversableMonadPlusOps<Option, A> {
B cata<B, B2 extends B>(B ifNone(), B2 ifSome(A a)) => fold(ifNone, ifSome);
Option<A> orElse(Option<A> other()) => fold(other, (_) => this);
A getOrElse(A dflt()) => fold(dflt, (a) => a);
A? get orNull => fold(() => null, id);
Either<B, A> toEither<B>(B ifNone()) => fold(() => left(ifNone()), (a) => right(a));
Either<dynamic, A> operator %(ifNone) => toEither(() => ifNone);
A operator |(A dflt) => getOrElse(() => dflt);
Expand Down
5 changes: 5 additions & 0 deletions test/either_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ void main() {
expect(r.ensure((x) => x < 0, () => 0), right(0));
});

test('getOrElseNull', () {
expect(left<String, int>('error').orNull, isNull);
expect(right<String, int>(42).orNull, 42);
});

group("EitherM", () => checkMonadLaws(EitherM));

//group("EitherTMonad+Id", () => checkMonadLaws(eitherTMonad(IdM)));
Expand Down
5 changes: 5 additions & 0 deletions test/option_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ void main() {
expect(Option.unless(true, 42), none());
});

test('orNull', () {
expect(none().orNull, isNull);
expect(some(42).orNull, 42);
});

group("OptionM", () => checkMonadLaws(new OptionMonadPlus()));

//group("OptionTMonad+Id", () => checkMonadLaws(optionTMonad(IdM)));
Expand Down

0 comments on commit ec80b9f

Please sign in to comment.