Skip to content

Commit

Permalink
Merge pull request #134 from projectdiscovery/feat-index-any
Browse files Browse the repository at this point in the history
Adding IndexAny strings helper
  • Loading branch information
Mzack9999 authored Apr 19, 2023
2 parents 4543cf4 + 0f3a0aa commit 1bc1ce6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions strings/stringsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,13 @@ func Truncate(data string, maxSize int) string {
}
return data
}

// IndexAny returns the index of the first instance of any of the specified substrings in s, or -1 if s does not contain any of the substrings.
func IndexAny(s string, seps ...string) (int, string) {
for _, sep := range seps {
if idx := strings.Index(s, sep); idx >= 0 {
return idx, sep
}
}
return -1, ""
}
18 changes: 18 additions & 0 deletions strings/stringsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,21 @@ func TestTruncate(t *testing.T) {
require.Equalf(t, test.result, res, "test:%s maxsize: %d result: %s", test.test, test.maxSize, res)
}
}

func TestIndexAny(t *testing.T) {
tests := []struct {
s string
seps []string
expectedIdx int
expectedSep string
}{
{"abcdefg", []string{"a", "b"}, 0, "a"},
{"abcdefg", []string{"z", "b"}, 1, "b"},
{"abcdefg", []string{"z", "zz"}, -1, ""},
}
for _, test := range tests {
idx, sep := IndexAny(test.s, test.seps...)
require.Equal(t, test.expectedIdx, idx)
require.Equal(t, test.expectedSep, sep)
}
}

0 comments on commit 1bc1ce6

Please sign in to comment.