Credence.Rule.NoSortForTopKReduce (credence v0.3.1)

Copy Markdown

Detects inefficient patterns where a full sort is performed only to retrieve a small number of elements (top-k) that cannot be reduced to a single Enum.min/1 or Enum.max/1 call.

Sorting an entire collection is O(n log n). When only a few elements are needed, a single-pass O(n) approach using Enum.reduce/3 is both faster and clearer in intent.

Flagged patterns

PatternSuggested replacement
Enum.sort/1 |> Enum.take(k) for k > 1Enum.reduce/3 (track top k)
Enum.sort/1 |> Enum.at(1)Enum.reduce/3 (track top two)

| (same patterns with Enum.reverse() before the terminal step) ||

These patterns are not automatically fixable because the correct replacement depends on the desired sort direction and requires a multi-step Enum.reduce/3 or min-heap approach.

Bad

Enum.sort(list) |> Enum.take(5)
Enum.sort(list) |> Enum.at(1)

Good

# Use Enum.reduce/3 to track the top-k elements in one pass