Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/elixir/lib/range.ex
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,14 @@ defmodule Range do
"""
@doc since: "1.14.0"
@spec shift(t, integer) :: t
def shift(first..last//step, steps_to_shift)
when is_integer(steps_to_shift) do
new(first + steps_to_shift * step, last + steps_to_shift * step, step)
def shift(range, steps_to_shift)

def shift(range, 0) when is_struct(range, Range), do: range
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
def shift(range, 0) when is_struct(range, Range), do: range
def shift(%Range{} = range, 0), do: range

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@josevalim I wanted to ask you if there's any performance difference doing pattern matches vs is_struct/2? Or it is just a matter of style.
Personally I favor the is_struct/2 approach as it declutter the function arguments section a bit.


def shift(first..last//step, steps_to_shift) when is_integer(steps_to_shift) do
shift = steps_to_shift * step

new(first + shift, last + shift, step)
end

@doc """
Expand Down
1 change: 1 addition & 0 deletions lib/elixir/test/elixir/range_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ defmodule RangeTest do

test "shift" do
assert Range.shift(0..10//2, 2) == 4..14//2
assert Range.shift(0..10//2, 0) == 0..10//2
assert Range.shift(10..0//-2, 2) == 6..-4//-2
assert Range.shift(10..0//-2, -2) == 14..4//-2
end
Expand Down