Skip to content

Commit

Permalink
make Literal::Array#push accept multiple values
Browse files Browse the repository at this point in the history
The current implementation of `#push` was only allowing for one value to
be passed in, but if the goal is to match ruby's functionality, then it
should accept multiple.

We also want to ensure that we perform the right type checking logic for
both scenarios.
  • Loading branch information
phillipspc committed Nov 11, 2024
1 parent 216dd5b commit fbd5c57
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/literal/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,17 @@ def &(other)
end
end

def push(value)
Literal.check(actual: value, expected: @__type__) do |c|
c.fill_receiver(receiver: self, method: "#push")
def push(*value)
case value
when ::Array
Literal::Array(@__type__).new(*value)
else
Literal.check(actual: value, expected: @__type__) do |c|
c.fill_receiver(receiver: self, method: "#push")
end
end

@__value__.push(value)
@__value__.push(*value)
self
end

Expand Down
19 changes: 19 additions & 0 deletions test/array.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,22 @@
assert Literal::Array(Integer) === result
expect(array.sort.to_a) == [1, 2, 3]
end

test "#push appends single value" do
array = Literal::Array(Integer).new(1, 2, 3)

expect((array.push(4)).to_a) == [1, 2, 3, 4]
end

test "#push appends multiple values" do
array = Literal::Array(Integer).new(1, 2, 3)

expect((array.push(4, 5)).to_a) == [1, 2, 3, 4, 5]
end

test "#push raises if any type is wrong" do
array = Literal::Array(Integer).new(1, 2, 3)

expect { array.push("4") }.to_raise(Literal::TypeError)
expect { array.push(4, "5") }.to_raise(Literal::TypeError)
end

0 comments on commit fbd5c57

Please sign in to comment.