I ran my code through SonarQube and it suggested me to reduce my code's cognitive complexity. I make use of quite a few nested loops, but I have tried to reduce it to the best of my abilities and would appreciate some suggestions. According to sonarqube I can reduce the complexity by at least two two levels.
I've commented the code and will post it below. The first snippet is the model that the function pulls from:
package model
type PrefilterEntry struct {
CustomerId string `bson:"customer_id"`
Timestamp string `bson:"timestamp"`
Prefilters []uint64 `bson:"prefilters"`
}
type Uint64Slice []uint64
func (p Uint64Slice) Len() int { return len(p) }
func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
This is the function in question:
func (s *service) checkMinimumPreFilters(ctx context.Context, uniquePrefilters []uint64, entries []model.PrefilterEntry, matchesNeeded float64) ([]string, error) {
if len(entries) == 0 {
err := errors.New("length of entries must be greater than 0")
s.logger.Error(ctx, "insufficient prefilters: ", err)
return []string{}, err
}
var customersMatched []string
for _, v := range entries {
sort.Sort(model.Uint64Slice(v.Prefilters))
preFilterMatches := 0
for _, j := range v.Prefilters {
for _, k := range uniquePrefilters {
if k > j {
break
}
if j == k {
preFilterMatches++
}
}
}
if float64(preFilterMatches) >= matchesNeeded {
customersMatched = append(customersMatched, v.CustomerId)
}
}
return customersMatched, nil
}
What I have tried:
I've tried reduce the complexity down to the best of my abilities, but I can't seem to keep it less than three nested loops.
Any suggestions would be greatly appreciated.