Class: Phamilie

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

Instance Method Summary collapse

Constructor Details

#initialize(cache = {}) ⇒ Phamilie

Returns a new instance of Phamilie.



2
3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/phamilie.rb', line 2

def initialize(cache = {})
  {:[] => 1, :[]= => 2}.each do |method, desired_arity|
    unless cache.respond_to?(method)
      raise ArgumentError.new("#{cache} does not respond to #{method}")
    end

    arity = cache.method(method).arity
    unless arity == desired_arity
      raise ArgumentError.new("#{cache} method #{method} arity should be #{desired_arity} instead of #{arity}")
    end
  end

  @cache = cache
end

Instance Method Details

#distance(path_a, path_b) ⇒ Object



41
42
43
# File 'lib/phamilie.rb', line 41

def distance(path_a, path_b)
  Fingerprint.distance(fingerprint(path_a), fingerprint(path_b))
end

#distance_with_rotations(path_a, path_b) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/phamilie.rb', line 45

def distance_with_rotations(path_a, path_b)
  if @cache[path_a].is_a?(Array) || @cache[path_b].is_a?(Integer)
    path_a, path_b = path_b, path_a
  end

  fingerprint_a = if @cache[path_a].is_a?(Integer)
    fingerprint(path_a)
  else
    rotations(path_a)[0]
  end

  rotations(path_b).map do |rotation_b|
    Fingerprint.distance(fingerprint_a, rotation_b)
  end.min
end

#fingerprint(path) ⇒ Object



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

def fingerprint(path)
  case cached = @cache[path]
  when Array
    cached[0]
  when Integer
    cached
  when nil
    @cache[path] = Fingerprint.fingerprint(path)
  else
    raise "Cache for #{path} contains non fingerprint #{cached}"
  end
end

#rotations(path) ⇒ Object



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

def rotations(path)
  case cached = @cache[path]
  when Array
    cached
  when Integer, nil
    @cache[path] = Fingerprint.rotations(path)
  else
    raise "Cache for #{path} contains non fingerprint #{cached}"
  end
end