From: amdahliu Date: Mon, 3 Jul 2023 10:09:36 +0000 (+0000) Subject: slices: refactor DeleteFunc to improve code readability X-Git-Tag: go1.22rc1~1590 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=47b403ad2dba61e653ec24da7d84cb9decea4939;p=gostls13.git slices: refactor DeleteFunc to improve code readability Reuse IndexFunc function to avoid confusing subscript indexing, and to reduce code nesting depth. Change-Id: I309416ebf928071f71054433e078f0fda802fba8 GitHub-Last-Rev: af54738bda7f27afda5f92496363c0a68493c369 GitHub-Pull-Request: golang/go#61154 Reviewed-on: https://go-review.googlesource.com/c/go/+/507635 Run-TryBot: Ian Lance Taylor Auto-Submit: Ian Lance Taylor Reviewed-by: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Heschi Kreinick TryBot-Result: Gopher Robot --- diff --git a/src/slices/slices.go b/src/slices/slices.go index afeed0afb5..725d91d8f5 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -228,21 +228,18 @@ func Delete[S ~[]E, E any](s S, i, j int) S { // zeroing those elements so that objects they reference can be garbage // collected. func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S { + i := IndexFunc(s, del) + if i == -1 { + return s + } // Don't start copying elements until we find one to delete. - for i, v := range s { - if del(v) { - j := i - for i++; i < len(s); i++ { - v = s[i] - if !del(v) { - s[j] = v - j++ - } - } - return s[:j] + for j := i + 1; j < len(s); j++ { + if v := s[j]; !del(v) { + s[i] = v + i++ } } - return s + return s[:i] } // Replace replaces the elements s[i:j] by the given v, and returns the