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 const constructor to None and getOrNull to Option #9

Open
wants to merge 3 commits 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
11 changes: 9 additions & 2 deletions lib/src/option.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'package:either_option/src/either.dart';

///Simple Option monad implementation
abstract class Option<A> {
const Option();

/// Return [None] Option
static Option<A> empty<A>() => _none();

Expand All @@ -17,10 +19,13 @@ abstract class Option<A> {
/// True if None else false
bool get isEmpty => !isDefined;

/// Return [a] inside [Some] else supplied [caseElse] if None
/// Return [a] inside [Some] else supplied [caseElse] if None
A? getOrElse(A? Function() caseElse) => fold(caseElse, (A a) => a);

/// Return inchanged Option if [Some] else supplied [caseElse] if None
/// Return [a] inside [Some] else null if None
A? getOrNull() => fold(() => null, (A a) => a);

/// Return unchanged Option if [Some] else supplied [caseElse] if None
Option orElse<B>(Option<B> Function() caseElse) =>
fold(caseElse, (A a) => this); // or (A a) => some(a)

Expand Down Expand Up @@ -78,6 +83,8 @@ class Some<A> extends Option<A> {
}

class None<A> extends Option<A> {
const None();

@override
bool operator ==(that) => that is None;

Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ environment:
sdk: ">=2.12.0 <3.0.0"

dependencies:
test: ^1.16.4
test: ">=1.21.0 <2.0.0"

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
6 changes: 5 additions & 1 deletion test/option_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,14 @@ void main() {
expect(a.fold(() => "ko", (_) => "ok"), "ko");
expect(b.fold(() => "ko", (_) => "ok"), "ok");

/// getorElse
/// getOrElse
expect(a.getOrElse(() => 0), 0);
expect(b.getOrElse(() => 0), 2);

/// getOrNull
expect(a.getOrNull(), null);
expect(b.getOrNull(), 2);

/// orElse
expect(a.orElse(() => Some("0")), Some("0"));
expect(b.orElse(() => Some(0)), Some(2));
Expand Down