Skip to content

Conversation

s3cur3
Copy link

@s3cur3 s3cur3 commented Jun 14, 2025

This expands the Credo.Check.Refactor.FilterFilter and related checks (FilterReject, RejectFilter, and RejectReject) to detect chains of the Map and Keyword versions of those functions in addition to Enum.

Thus, we can now detect all three of:

ints
|> Enum.filter(&even?/1)
|> Enum.filter(fn val -> val > 0 end)

map
|> Map.filter(fn {key, _val} -> is_binary(key) end)
|> Map.filter(fn {_key, val} -> val > 0 end)

keyword
|> Keyword.filter(fn {key, _val} -> key in [:a, :b, :c] end)
|> Keyword.filter(fn {_key, val} -> val > 0 end)

This expands the `Credo.Check.Refactor.FilterFilter` and related checks (`FilterReject`, `RejectFilter`, and `RejectReject`) to detect chains of the `Map` and `Keyword` versions of those functions in addition to `Enum`.

Thus, we can now detect all three of:

```elixir
ints
|> Enum.filter(&even?/1)
|> Enum.filter(fn val -> val > 0 end)

map
|> Map.filter(fn {key, _val} -> is_binary(key) end)
|> Map.filter(fn {_key, val} -> val > 0 end)

keyword
|> Keyword.filter(fn {key, _val} -> key in [:a, :b, :c] end)
|> Keyword.filter(fn {_key, val} -> val > 0 end)
```
Comment on lines +1 to +15
defmodule Credo.Check.Refactor.KeywordHelpers do
def traverse(
{{:., _, [{:__aliases__, meta, [:Keyword]}, second]}, _,
[{{:., _, [{:__aliases__, _, [:Keyword]}, first]}, _, _}, _]} = ast,
issues,
issue_meta,
message,
trigger,
first,
second,
module
) do
new_issue = issue_for(issue_meta, meta[:line], message, trigger, module)
{ast, issues ++ List.wrap(new_issue)}
end
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This module, as well as the MapHelpers below, is a straight copy and paste of EnumHelpers, with the module name changed.

My sense based on reading the rest of the codebase was that duplication was preferable to either

  • metaprogramming to generate a KeywordHelpers and MapHelpers module, or
  • making a single, more generic module that accept the target module (:Enum, :Map, or :Keyword) as an argument

If I'm mistaken, though, I'm happy to do that refactor.

@s3cur3 s3cur3 marked this pull request as ready for review June 14, 2025 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant