Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 15 additions & 3 deletions lib/json-compare/comparer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,30 @@ def compare_arrays(old_array, new_array)

result = get_diffs_struct

(0..inters).map do |n|
(1..inters).map do |n|
res = compare_elements(old_array[-n], new_array[-n])
if res.nil? || (res.respond_to?(:empty?) && res.empty?)
old_array_length -= 1
new_array_length -= 1
else
break
end
end

inters = [old_array_length, new_array_length].min

(0..(inters - 1)).map do |n|
res = compare_elements(old_array[n], new_array[n])
result[:update][n] = res unless (res.nil? || (res.respond_to?(:empty?) && res.empty?))
end

# the rest of the larger array
if inters == old_array_length
(inters..new_array_length).each do |n|
(inters..(new_array_length - 1)).each do |n|
result[:append][n] = new_array[n]
end
else
(inters..old_array_length).each do |n|
(inters..(old_array_length - 1)).each do |n|
result[:remove][n] = old_array[n]
end
end
Expand Down
14 changes: 12 additions & 2 deletions spec/lib/json-compare_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,18 @@
end

it "should compare arrays of fixnums" do
result = JsonCompare.get_diff([1, 2, 3], [1, 2, 3, 4])
result.should eq(:append => { 3 => 4 }, :update => { 3 => 4 })
result = JsonCompare.get_diff([1, 2, 3], [1, 2, 3, 4, 5])
result.should eq(:append => { 3 => 4, 4 => 5 })
end

it "should compare arrays of remove last element" do
result = JsonCompare.get_diff([1, 2, 3, 4, 5], [1, 2, 3])
result.should eq(:remove => { 3 => 4, 4 => 5 })
end

it "should compare arrays of remove hash" do
result = JsonCompare.get_diff([{"a"=>1}, {"a"=>2}, {"a"=>3}, {"a"=>4}, {"a"=>5}], [{"a"=>1}, {"a"=>2}, {"a"=>3}, {"a"=>5}])
result.should eq(:remove => { 3 => {"a"=>4} })
end
end

Expand Down