Skip to content

Commit

Permalink
add lets.Val(...) function
Browse files Browse the repository at this point in the history
  • Loading branch information
alimy committed Jun 4, 2024
1 parent 9acf998 commit 92ff535
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 8 additions & 0 deletions lets/lets.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,11 @@ func If[T any](condition bool, trueVal, falseVal T) T {
}
return falseVal
}

// Val[T] return s[0] if s is give or else return v
func Val[T any](v T, s ...T) T {
if len(s) > 0 {
return s[0]
}
return v
}
22 changes: 20 additions & 2 deletions lets/lets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
// Use of this source code is governed by Apache License 2.0 that
// can be found in the LICENSE file.

package lets
package lets_test

import (
"testing"

"github.com/alimy/tryst/lets"
)

func TestIf(t *testing.T) {
Expand All @@ -18,8 +20,24 @@ func TestIf(t *testing.T) {
{true, 1, 2, 1},
{false, 1, 2, 2},
} {
if res := If(tc.condition, tc.trueVal, tc.falseVal); res != tc.result {
if res := lets.If(tc.condition, tc.trueVal, tc.falseVal); res != tc.result {
t.Errorf("If(%t, %d, %d) want %d but got %d", tc.condition, tc.trueVal, tc.falseVal, tc.result, res)
}
}
}

func TestVal(t *testing.T) {
for _, tc := range []struct {
v int
s []int
r int
}{
{4, []int{5, 6}, 5},
{4, []int{5}, 5},
{5, []int{}, 5},
} {
if res := lets.Val(tc.v, tc.s...); res != tc.r {
t.Errorf("give v:%d s:%+v want: %d but got %d", tc.v, tc.s, tc.r, res)
}
}
}

0 comments on commit 92ff535

Please sign in to comment.