From ec80b9f0ab2e2a92e4b17b6c267f56d4c6987626 Mon Sep 17 00:00:00 2001 From: Ian McIntosh Date: Fri, 14 Jan 2022 11:42:30 -0500 Subject: [PATCH] Add [Either,Option].orNull. Closes #86. --- lib/src/either.dart | 1 + lib/src/option.dart | 1 + test/either_test.dart | 5 +++++ test/option_test.dart | 5 +++++ 4 files changed, 12 insertions(+) diff --git a/lib/src/either.dart b/lib/src/either.dart index 2ee5b58..fa835ce 100644 --- a/lib/src/either.dart +++ b/lib/src/either.dart @@ -9,6 +9,7 @@ abstract class Either implements TraversableMonadOps, R Either orElse(Either other()) => fold((_) => other(), (_) => this); R getOrElse(R dflt()) => fold((_) => dflt(), id); + R? get orNull => fold((_) => null, id); R operator |(R dflt) => getOrElse(() => dflt); Either leftMap(L2 f(L l)) => fold((L l) => left(f(l)), right); Option toOption() => fold((_) => none(), some); diff --git a/lib/src/option.dart b/lib/src/option.dart index 6cfdab9..dc4078f 100644 --- a/lib/src/option.dart +++ b/lib/src/option.dart @@ -10,6 +10,7 @@ abstract class Option implements TraversableMonadPlusOps { B cata(B ifNone(), B2 ifSome(A a)) => fold(ifNone, ifSome); Option orElse(Option other()) => fold(other, (_) => this); A getOrElse(A dflt()) => fold(dflt, (a) => a); + A? get orNull => fold(() => null, id); Either toEither(B ifNone()) => fold(() => left(ifNone()), (a) => right(a)); Either operator %(ifNone) => toEither(() => ifNone); A operator |(A dflt) => getOrElse(() => dflt); diff --git a/test/either_test.dart b/test/either_test.dart index 6461710..63b83e8 100644 --- a/test/either_test.dart +++ b/test/either_test.dart @@ -71,6 +71,11 @@ void main() { expect(r.ensure((x) => x < 0, () => 0), right(0)); }); + test('getOrElseNull', () { + expect(left('error').orNull, isNull); + expect(right(42).orNull, 42); + }); + group("EitherM", () => checkMonadLaws(EitherM)); //group("EitherTMonad+Id", () => checkMonadLaws(eitherTMonad(IdM))); diff --git a/test/option_test.dart b/test/option_test.dart index 915e294..4ea0468 100644 --- a/test/option_test.dart +++ b/test/option_test.dart @@ -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)));