Credence.Pattern.PreferEnumSlice
(credence v0.7.1)
Copy Markdown
Readability rule: flags Enum.drop/2 followed by Enum.take/2 and rewrites it
to Enum.slice/3.
Enum.drop(list, start) |> Enum.take(len) keeps elements [start, start+len),
which is exactly Enum.slice(list, start, len) — but only when both start
and len are non-negative. With a negative start, Enum.drop counts from
the end while Enum.slice's start indexes from the end differently; with a
negative len, Enum.take keeps the last len while Enum.slice rejects a
negative length. So the rule fires only when both amounts are non-negative
integer literals — a variable amount could be negative at runtime and is not
rewritten.
Bad
Enum.drop(list, 5) |> Enum.take(10)
Enum.take(Enum.drop(list, 5), 10)Good
Enum.slice(list, 5, 10)Not flagged
Enum.drop(list, start) |> Enum.take(len) # variable amounts (could be negative)
Enum.drop(list, -1) |> Enum.take(2) # negative drop
Enum.drop(list, 1) |> Enum.take(-2) # negative take