Credence.Rule.NoEnumDropNegative (credence v0.2.0)

Copy Markdown

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

For linked lists, Enum.drop(list, -n) must traverse to the end of the list to figure out where to cut, making it O(n). This often indicates the algorithm should be restructured to avoid needing to trim from the tail of a linked list.

Bad

list |> Enum.drop(-1)

Good

# If building the list yourself, drop the head before reversing:
[_ | rest] = reversed_list
Enum.reverse(rest)

# Or use Enum.slice/2 if you know the desired length:
Enum.slice(list, 0..-2//1)