opt.Optional[T].Filter()

master
Charles Iliya Krempeaux 2022-08-14 00:58:41 -07:00
parent 4cd974c11f
commit bb61bb0854
2 changed files with 100 additions and 1 deletions

View File

@ -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:
//

View File

@ -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
}
}
}