From 2e30aac2208cba15f0839ea4a2a90ebd9ce2182b Mon Sep 17 00:00:00 2001 From: nickolasdaniel Date: Thu, 15 Jul 2021 16:52:50 +0300 Subject: [PATCH] Added FirstIntNonEmpty and FirstDurationNonEmpty functions in utils --- utils/coreutils.go | 18 +++++++++++++++ utils/coreutils_test.go | 51 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/utils/coreutils.go b/utils/coreutils.go index 2dc6c11e8..6a7def13e 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -120,6 +120,24 @@ func FirstNonEmpty(vals ...string) string { return EmptyString } +func FirstIntNonEmpty(vals ...int) int { + for _, val := range vals { + if val != 0 { + return val + } + } + return 0 +} + +func FirstDurationNonEmpty(vals ...time.Duration) time.Duration { + for _, val := range vals { + if val != 0 { + return val + } + } + return 0 +} + // Sha1 generate the SHA1 hash from any string // the order of string matters func Sha1(attrs ...string) string { diff --git a/utils/coreutils_test.go b/utils/coreutils_test.go index 041e1db35..e8ff12a5b 100644 --- a/utils/coreutils_test.go +++ b/utils/coreutils_test.go @@ -57,6 +57,57 @@ func TestFirstNonEmpty(t *testing.T) { } } +func TestFirstIntNonEmpty(t *testing.T) { + //check for default value + rcv := FirstIntNonEmpty(0) + if rcv != 0 { + t.Errorf("Expected 0 \n but received \n %d", rcv) + } + + //case the first non empty value is on the first position + rcv = FirstIntNonEmpty(21, 0, 0) + if rcv != 21 { + t.Errorf("Expected 21 \n but received \n %d", rcv) + } + + //case the first non empty value is on the second position + rcv = FirstIntNonEmpty(0, 21, 0) + if rcv != 21 { + t.Errorf("Expected 21 \n but received \n %d", rcv) + } + + //case the first non empty value is on the third position + rcv = FirstIntNonEmpty(0, 0, 21) + if rcv != 21 { + t.Errorf("Expected 21 \n but received \n %d", rcv) + } +} + +func TestFirstDurationNonEmpty(t *testing.T) { + //check for default value + rcv := FirstDurationNonEmpty(0) + if rcv != 0 { + t.Errorf("Expected 0 \n but received \n %d", rcv) + } + + //case the first non empty value is on the first position + rcv = FirstDurationNonEmpty(2*time.Minute, 0, 0) + if rcv != 2*time.Minute { + t.Errorf("Expected 2m \n but received \n %d", rcv) + } + + //case the first non empty value is on the second position + rcv = FirstDurationNonEmpty(0, 2*time.Minute, 0) + if rcv != 2*time.Minute { + t.Errorf("Expected 2m \n but received \n %d", rcv) + } + + //case the first non empty value is on the third position + rcv = FirstDurationNonEmpty(0, 0, 2*time.Minute) + if rcv != 2*time.Minute { + t.Errorf("Expected 2m \n but received \n %d", rcv) + } +} func TestSha1(t *testing.T) { //empty check rcv := Sha1(" ")