Skip to content

Commit

Permalink
feat(retrieve): adding GetOrElse (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Mar 9, 2020
1 parent 8c9292a commit ab9f5b8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
14 changes: 14 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,20 @@ Retrieves the value at path of struct(s).
funk.Get([]*Foo{foo1, foo2}, "Bar.Name") // []string{"Test"}
funk.Get(foo2, "Bar.Name") // nil
funk.GetOrElse
.........

Retrieves the value of the pointer or default.

.. code-block:: go
str := "hello world"
GetOrElse(&str, "foobar") // string{"hello world"}
GetOrElse(str, "foobar") // string{"hello world"}
GetOrElse(nil, "foobar") // string{"foobar"}
funk.Keys
.........

Expand Down
15 changes: 13 additions & 2 deletions retrieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ func get(value reflect.Value, path string) reflect.Value {
var resultSlice reflect.Value

length := value.Len()

if length == 0 {
return resultSlice
}

for i := 0; i < length; i++ {
item := value.Index(i)

Expand Down Expand Up @@ -77,3 +77,14 @@ func get(value reflect.Value, path string) reflect.Value {

return value
}

// Get retrieves the value of the pointer or default.
func GetOrElse(v interface{}, def interface{}) interface{} {
val := reflect.ValueOf(v)
if v == nil {
return def
} else if val.Kind() != reflect.Ptr {
return v
}
return val.Elem().Interface()
}
9 changes: 9 additions & 0 deletions retrieve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,12 @@ func TestGetSimple(t *testing.T) {

is.Equal(result, []string{"Level1-1", "Level1-2"})
}

func TestGetOrElse(t *testing.T) {
is := assert.New(t)

str := "hello world"
is.Equal("hello world", GetOrElse(&str, "foobar"))
is.Equal("hello world", GetOrElse(str, "foobar"))
is.Equal("foobar", GetOrElse(nil, "foobar"))
}

0 comments on commit ab9f5b8

Please sign in to comment.