Credence.Pattern.NoSortForTopK
(credence v0.5.0)
Copy Markdown
Detects inefficient patterns where a full sort is performed only to retrieve a single element (the minimum or maximum).
Sorting an entire collection is O(n log n). When only the minimum or
maximum element is needed, Enum.min/1 or Enum.max/1 provides the
same result in O(n) without allocating a sorted intermediate list.
Flagged patterns
| Pattern | Suggested replacement |
|---|
| `Enum.sort/1 | > Enum.take(1)` | Enum.min/1 |
| `Enum.sort/1 | > hd/1` | Enum.min/1 |
| `Enum.sort/1 | > Enum.at(0)` | Enum.min/1 |
| `Enum.sort/1 | > Enum.reverse() | > Enum.take(1)` | Enum.max/1 |
| `Enum.sort/1 | > Enum.reverse() | > hd/1` | Enum.max/1 |
| `Enum.sort/1 | > Enum.reverse() | > Enum.at(0)` | Enum.max/1 |
These patterns are automatically fixable.
Bad
Enum.sort(list) |> Enum.take(1)
Enum.sort(list) |> Enum.reverse() |> hd()Good
Enum.min(list)
Enum.max(list)