Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add [Either,Option].orNull. Closes #86. #99

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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