diff --git a/lib/json-compare/comparer.rb b/lib/json-compare/comparer.rb index d2b3c71..e542f11 100644 --- a/lib/json-compare/comparer.rb +++ b/lib/json-compare/comparer.rb @@ -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 diff --git a/spec/lib/json-compare_spec.rb b/spec/lib/json-compare_spec.rb index bfe373a..17b1565 100644 --- a/spec/lib/json-compare_spec.rb +++ b/spec/lib/json-compare_spec.rb @@ -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