From bb61bb0854d89b2ae8fcec30f0debcb98f974a54 Mon Sep 17 00:00:00 2001 From: Charles Iliya Krempeaux Date: Sun, 14 Aug 2022 00:58:41 -0700 Subject: [PATCH] opt.Optional[T].Filter() --- optional.go | 40 ++++++++++++++++++++++++++- optional_filter_test.go | 61 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 optional_filter_test.go diff --git a/optional.go b/optional.go index e467800..e46dafc 100644 --- a/optional.go +++ b/optional.go @@ -80,7 +80,45 @@ func Something[T any](value T) Optional[T] { } } -// Get return the value inside of the optional-type if it is holding something. +// Filter returns itself if it is holding something and ‘fn’ applied to its value returns true. +// Else it return nothing. +// +// For example: +// +// fn := func(value int) bool { +// return 0 == (value % 2) +// } +// +// // ... +// +// var op1 opt.Optional[int] = opt.Something[int](10) +// +// op1 = op1.Filter(fn) +// +// // ... +// +// var op2 opt.Optional[int] = opt.Something[int](11) +// +// op2 = op2.Filter(fn) +// +// // ... +// +// var op3 opt.Optional[int] = opt.Nothing[int]() +// +// op3 = op3.Filter(fn) +func (receiver Optional[T]) Filter(fn func(T)bool) Optional[T] { + if !receiver.something { + return Nothing[T]() + } + + if !fn(receiver.value) { + return Nothing[T]() + } + + return receiver +} + +// Get returns the value inside of the optional-type if it is holding something. // // Example usage: // diff --git a/optional_filter_test.go b/optional_filter_test.go new file mode 100644 index 0000000..76f6b8c --- /dev/null +++ b/optional_filter_test.go @@ -0,0 +1,61 @@ +package opt_test + +import ( + "github.com/reiver/go-opt" + + "testing" +) + +func TestOptional_Filter_int(t *testing.T) { + + tests := []struct{ + Optional opt.Optional[int] + Expected opt.Optional[int] + }{ + { + Optional: opt.Nothing[int](), + Expected: opt.Nothing[int](), + }, + + + + { + Optional: opt.Something[int](-2), + Expected: opt.Something[int](-2), + }, + { + Optional: opt.Something[int](-1), + Expected: opt.Nothing[int](), + }, + { + Optional: opt.Something[int](0), + Expected: opt.Something[int](0), + }, + { + Optional: opt.Something[int](1), + Expected: opt.Nothing[int](), + }, + { + Optional: opt.Something[int](2), + Expected: opt.Something[int](2), + }, + } + + for testNumber, test := range tests { + + fn := func(value int) bool { + return 0 == (value % 2) + } + + actual := test.Optional.Filter(fn) + expected := test.Expected + + if expected != actual { + t.Errorf("For test #%d, the actual value is not what was expected.", testNumber) + t.Logf("EXPECTED: %#v", expected) + t.Logf("ACTUAL: %#v", actual) + /////////////// CONTINUE + continue + } + } +}