Skip to content

Commit

Permalink
if not x, do: y => unless x, do: y
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jan 25, 2024
1 parent b01d328 commit 7704a35
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
### Improvements

* deprecations: `~R` -> `~r`, `Date.range/2` -> `Date.range/3` with decreasing dates (h/t @milmazz)
* if: rewrite `if not x, do: y` => `unless x, do: y`
* pipes: `|> Enum.map(foo) |> Map.new()` => `|> Map.new(foo)`
* pipes: remove unnecessary `then/2` on named function captures: `|> then(&foo/1)` => `|> foo()`, `|> then(&foo(&1, ...))` => `|> foo(...)` (thanks to @tfiedlerdejanze for the idea + impl!)

## v0.11.6

Expand Down
4 changes: 4 additions & 0 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ defmodule Styler.Style.Blocks do
[{negator, _, [expr]}, [{do_, do_body}, {else_, else_body}]] when is_negator(negator) ->
zipper |> Zipper.replace({:if, m, [expr, [{do_, else_body}, {else_, do_body}]]}) |> run(ctx)

# if not x, do: y => unless x, do: y
[{negator, _, [expr]}, [do_block]] when is_negator(negator) ->
zipper |> Zipper.replace({:unless, m, [expr, [do_block]]}) |> run(ctx)

# drop `else: nil`
[head, [do_block, {_, {:__block__, _, [nil]}}]] ->
{:cont, Zipper.replace(zipper, {:if, m, [head, [do_block]]}), ctx}
Expand Down
13 changes: 6 additions & 7 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,12 @@ defmodule Styler.Style.BlocksTest do
""")
end

test "if not => unless" do
assert_style("if not x, do: y", "unless x, do: y")
assert_style("if !x, do: y", "unless x, do: y")
assert_style("if !!x, do: y", "if x, do: y")
end

test "Credo.Check.Refactor.UnlessWithElse" do
for negator <- ["!", "not "] do
assert_style(
Expand Down Expand Up @@ -826,15 +832,8 @@ defmodule Styler.Style.BlocksTest do

test "Credo.Check.Refactor.NegatedConditionsWithElse" do
for negator <- ["!", "not "] do
assert_style("if #{negator}foo, do: :bar")
assert_style("if #{negator}foo, do: :bar, else: :baz", "if foo, do: :baz, else: :bar")

assert_style("""
if #{negator}foo do
bar
end
""")

assert_style(
"""
if #{negator}foo do
Expand Down

0 comments on commit 7704a35

Please sign in to comment.