Credence.Rule.NoEnumTakeNegative (credence v0.3.0)

Copy Markdown

Performance rule: Detects Enum.take(list, -n) where n is a positive integer literal.

For linked lists, Enum.take(list, -n) must internally determine the list length, then traverse again to the cut point — effectively two full traversals. If the list was just sorted, sorting in the opposite direction and taking a positive count is more efficient.

The auto-fix replaces Enum.take(list, -n) with Enum.slice(list, -n..-1//1), which has equivalent semantics and makes the tail-access explicit.

Bad

sorted = Enum.sort(nums)
top_three = Enum.take(sorted, -3)

Good

top_three = Enum.sort(nums, :desc) |> Enum.take(3)

# Or use Enum.slice/2 to be explicit about the range:
Enum.slice(sorted, -3..-1//1)