diff --git a/lib/literal/array.rb b/lib/literal/array.rb index 4e8ee49..681b767 100644 --- a/lib/literal/array.rb +++ b/lib/literal/array.rb @@ -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) @@ -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 @@ -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, &) diff --git a/test/array.test.rb b/test/array.test.rb index 7ff1aa5..cd501b9 100644 --- a/test/array.test.rb +++ b/test/array.test.rb @@ -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