Created
June 12, 2019 21:21
-
-
Save cacheflow/f42210453a7a6e7f56ab83987e5f91a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Differ | |
attr_reader :data1, :data2 | |
def initialize(data1, data2) | |
if data1 === nil || data2 === nil | |
raise ArgumentError.new("Can't diff nil values") | |
end | |
@data1 = data1 | |
@data2 = data2 | |
check_matching_parameters | |
end | |
def check_matching_parameters | |
type_1 = find_matching_type(data1) | |
type_2 = find_matching_type(data2) | |
if type_1 != type_2 | |
raise ArgumentError.new("Can't diff parameters that are not of the same type") | |
end | |
end | |
def find_matching_type(data) | |
[String, Set, SortedSet, Hash, Array].select do |type| | |
data.is_a?(type) | |
end.first || "" | |
end | |
def are_sets? | |
@data1.is_a?(Set) && @data2.is_a?(Set) | |
end | |
def are_hashes? | |
@data1.is_a?(Hash) && @data2.is_a?(Hash) | |
end | |
def are_sorted_sets? | |
@data1.is_a?(SortedSet) && @data2.is_a?(SortedSet) | |
end | |
def are_arrays? | |
@data1.is_a?(Array) && @data2.is_a?(Array) | |
end | |
def are_strings? | |
@data1.is_a?(String) && @data2.is_a?(String) | |
end | |
def diff_sets | |
data2.difference(data1) | |
end | |
def diff_arrays(first = data1, second = data2) | |
(second + first) - (second & first) | |
end | |
def diff_sorted_sets | |
diff_arrays(HashWithIndifferentAccess(data1).to_a, HashWithIndifferentAccess(data2).to_a) | |
end | |
def diff_hashes | |
h = {}; | |
diff_arrays(data1.to_a, data2.to_a).flatten.each do |data| | |
if data2[data].present? | |
h[data.to_s] = data2[data] | |
end | |
end | |
h | |
end | |
def diff_strings | |
data1_arr = data1.split('').collect(&:strip) | |
data2_arr = data2.split('').collect(&:strip) | |
diff_arrays(data1_arr, data2_arr).join('') | |
end | |
def diff | |
if are_arrays? | |
diff_arrays | |
elsif are_hashes? | |
diff_hashes | |
elsif are_sorted_sets? | |
diff_sorted_sets | |
elsif are_sets? | |
diff_sets | |
elsif are_strings? | |
diff_strings | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment