Skip to content

Commit

Permalink
Merge pull request #91 from projectdiscovery/issue-90-equals-any-all
Browse files Browse the repository at this point in the history
Add generic comparison helper function
  • Loading branch information
Mzack9999 authored Feb 26, 2023
2 parents 729c195 + b395498 commit b17bec2
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
26 changes: 26 additions & 0 deletions generic/generic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package generic

// EqualsAny checks if a base value of type T is equal to
// any of the other values of type T provided as arguments.
func EqualsAny[T comparable](base T, all ...T) bool {
for _, v := range all {
if v == base {
return true
}
}
return false
}

// EqualsAll checks if a base value of type T is equal to all of the
// other values of type T provided as arguments.
func EqualsAll[T comparable](base T, all ...T) bool {
if len(all) == 0 {
return false
}
for _, v := range all {
if v != base {
return false
}
}
return true
}
77 changes: 77 additions & 0 deletions generic/generic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package generic

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestEqualsAnyInt(t *testing.T) {
testCases := []struct {
Base int
All []int
Expected bool
}{
{3, []int{1, 2, 3, 4}, true},
{5, []int{1, 2, 3, 4}, false},
{0, []int{0}, true},
{0, []int{1}, false},
}

for _, tc := range testCases {
actual := EqualsAny(tc.Base, tc.All...)
require.Equal(t, tc.Expected, actual)
}
}

func TestEqualsAnyString(t *testing.T) {
testCases := []struct {
Base string
All []string
Expected bool
}{
{"test", []string{"test1", "test", "test2", "test3"}, true},
{"test", []string{"test1", "test2", "test3", "test4"}, false},
{"", []string{""}, true},
{"", []string{"not empty"}, false},
}

for _, tc := range testCases {
actual := EqualsAny(tc.Base, tc.All...)
require.Equal(t, tc.Expected, actual)
}
}

func TestEqualsAllInt(t *testing.T) {
testCases := []struct {
Base int
All []int
Expected bool
}{
{5, []int{5, 5, 5, 5}, true},
{5, []int{1, 2, 3, 4}, false},
{0, []int{}, false},
}

for _, tc := range testCases {
actual := EqualsAll(tc.Base, tc.All...)
require.Equal(t, tc.Expected, actual)
}
}

func TestEqualsAllString(t *testing.T) {
testCases := []struct {
Base string
All []string
Expected bool
}{
{"test", []string{"test", "test", "test", "test"}, true},
{"test", []string{"test", "test1", "test2", "test3"}, false},
{"", []string{}, false},
}

for _, tc := range testCases {
actual := EqualsAll(tc.Base, tc.All...)
require.Equal(t, tc.Expected, actual)
}
}

0 comments on commit b17bec2

Please sign in to comment.