Class: Camille::IntersectionSolver

Inherits:
Object
  • Object
show all
Defined in:
lib/camille/intersection_solver.rb

Defined Under Namespace

Classes: TypeNotCompatibleError

Class Method Summary collapse

Class Method Details

.solve(a, b) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/camille/intersection_solver.rb', line 6

def solve a, b
  if a.instance_of?(Camille::Types::Object) && b.instance_of?(Camille::Types::Object)
    overlapping_keys = a.fields.keys & b.fields.keys

    new_fields = []
    new_optional_keys = []

    [a, b].each do |x|
      (x.fields.keys - overlapping_keys).each do |key|
        new_fields << [key, x.fields[key]]
        new_optional_keys << key if x.optional_keys.include?(key)
      end
    end

    overlapping_keys.map do |key|
      solved = IntersectionSolver.solve(a.fields[key], b.fields[key])
      new_fields << [key, solved]
      if a.optional_keys.include?(key) && b.optional_keys.include?(key)
        new_optional_keys << key
      end
    end

    Camille::Types::Object.new(**(apply_optional_to_fields new_fields, new_optional_keys).to_h)
  else
    if a.literal == b.literal
      a
    else
      raise TypeNotCompatibleError.new "Cannot reconcile type #{a.literal} and type #{b.literal}."
    end
  end
end