Module: Consimilo

Defined in:
lib/consimilo.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.difference(left, right, order: true, compact: false) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/consimilo.rb', line 17

def difference(left, right, order: true, compact: false)
  if is_array?(left) && is_array?(right)
    result = difference_array(left, right, order: order, compact: compact)
    return result.flatten.empty? ? [] : result
  end

  if is_hash?(left) && is_hash?(right)
    return difference_hash(left, right, order: order, compact: compact)
  end

  [left, right]
end

.difference_array(left, right, order: true, compact: false) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/consimilo.rb', line 39

def difference_array(left, right, order: true, compact: false)
  unless order
    left = left.sort
    right = right.sort
  end

  (0...[left.size, right.size].max).each_with_object([]) do |index, diff|
    if left[index] == right[index]
      next compact ? diff : diff.push([])
    end

    difference = difference(left[index], right[index], order: order, compact: compact)
    next diff if difference.empty? && compact
    diff.push(difference)
  end
end

.difference_hash(left, right, order: true, compact: false) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/consimilo.rb', line 30

def difference_hash(left, right, order: true, compact: false)
  (left.keys | right.keys).each_with_object({}) do |key, diff|
    next if left[key] == right[key]
    difference = difference(left[key], right[key], order: order, compact: compact)
    next if difference.empty?
    diff[key] = difference
  end
end

.is_array?(instance) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/consimilo.rb', line 9

def is_array?(instance)
  instance.is_a?(Array)
end

.is_hash?(instance) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/consimilo.rb', line 13

def is_hash?(instance)
  instance.is_a?(Hash)
end