-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #76 from Teamwork/enhancement/default
Enhancement: `Default`
- Loading branch information
Showing
5 changed files
with
53 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
// Package typeutil adds functions for types. | ||
package typeutil // import "github.com/teamwork/utils/v2/typeutil" | ||
|
||
// Default returns `val` if it is not zero, otherwise returns | ||
// `def`. | ||
// | ||
// v := Default("", "hello") // return "hello" | ||
// v := Default("world", "hello") // return "world" | ||
func Default[T comparable](val, def T) T { | ||
if val == *new(T) { | ||
return def | ||
} | ||
|
||
return val | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package typeutil_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/teamwork/utils/v2/typeutil" | ||
) | ||
|
||
func Test_Default(t *testing.T) { | ||
tests := map[string]struct { | ||
in string | ||
exp string | ||
}{ | ||
"empty string returns default": { | ||
in: "", | ||
exp: "default value", | ||
}, | ||
"non-empty string returns value": { | ||
in: "hello there", | ||
exp: "hello there", | ||
}, | ||
} | ||
|
||
for name, test := range tests { | ||
test := test | ||
t.Run(name, func(t *testing.T) { | ||
t.Parallel() | ||
|
||
if val := typeutil.Default(test.in, "default value"); val != test.exp { | ||
t.Fatalf("expected '%s', got '%s'", test.exp, val) | ||
} | ||
}) | ||
} | ||
} |