Skip to content

Commit

Permalink
Implement Literal::Array#compact and #compact!
Browse files Browse the repository at this point in the history
  • Loading branch information
christopher-b committed Nov 12, 2024
1 parent dba71f8 commit 60195a5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
32 changes: 27 additions & 5 deletions lib/literal/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,29 @@ def *(times)
end
end

def +(other)
case other
when ::Array
values = @__value__ + @__generic__.new(*other).__value__
when Literal::Array
values = @__value__ + other.__value__
else
raise ArgumentError, "Cannot perform `+` with #{other.class.name}."
end

Literal::Array.new(values, type: @__type__)
end

def +(other)
case other
when ::Array
other = @__generic__.new(*other)
Literal::Array.new(@__value__ + other.__value__, type: @__type__)
when Literal::Array
# Do nothing
Literal::Array.new(@__value__ + other.__value__, type: @__type__)
else
raise ArgumentError.new("Cannot perform `+` with #{other.class.name}.")
end

Literal::Array.new(@__value__ + other.__value__, type: @__type__)
end

def -(other)
Expand Down Expand Up @@ -156,6 +168,16 @@ def clear(...)
self
end

def compact
# @TODO if this is an array of nils, we should return an emtpy array
__with__(@__value__)
end

def compact!
# @TODO if this is an array of nils, we should set @__value__ = [] and return self
nil
end

def count(...)
@__value__.count(...)
end
Expand Down Expand Up @@ -199,8 +221,8 @@ def map(type, &)
end

def map!(&)
new_array = map(@__type__, &)
@__value__ = new_array.__value__
new_array = map(@__type__, &)
@__value__ = new_array.__value__
end

def max(n = nil, &)
Expand Down
13 changes: 13 additions & 0 deletions test/array.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,16 @@
expect(array.assoc(1)) == [1, 2]
expect(array.assoc(3)) == [3, 4]
end

test "#compact returns a new Literal::Array" do
array = Literal::Array(Integer).new(1, 2, 3)

expect(array.compact.to_a) == [1, 2, 3]
expect(array.compact) != array
end

test "#compact! returns nil" do
array = Literal::Array(Integer).new(1, 2, 3)

expect(array.compact!) == nil
end

0 comments on commit 60195a5

Please sign in to comment.