mirror of
https://github.com/golang/go
synced 2024-11-26 20:11:26 -07:00
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: af54738bda
GitHub-Pull-Request: golang/go#61154
Reviewed-on: https://go-review.googlesource.com/c/go/+/507635
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
This commit is contained in:
parent
2627d2d189
commit
47b403ad2d
@ -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
|
// zeroing those elements so that objects they reference can be garbage
|
||||||
// collected.
|
// collected.
|
||||||
func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
|
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.
|
// Don't start copying elements until we find one to delete.
|
||||||
for i, v := range s {
|
for j := i + 1; j < len(s); j++ {
|
||||||
if del(v) {
|
if v := s[j]; !del(v) {
|
||||||
j := i
|
s[i] = v
|
||||||
for i++; i < len(s); i++ {
|
i++
|
||||||
v = s[i]
|
|
||||||
if !del(v) {
|
|
||||||
s[j] = v
|
|
||||||
j++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s[:j]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return s
|
return s[:i]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace replaces the elements s[i:j] by the given v, and returns the
|
// Replace replaces the elements s[i:j] by the given v, and returns the
|
||||||
|
Loading…
Reference in New Issue
Block a user