Class: Factbase::IndexedLt

Inherits:
Object
  • Object
show all
Defined in:
lib/factbase/indexed/indexed_lt.rb

Overview

Indexed term ‘lt’.

Instance Method Summary collapse

Constructor Details

#initialize(term, idx) ⇒ IndexedLt



8
9
10
11
# File 'lib/factbase/indexed/indexed_lt.rb', line 8

def initialize(term, idx)
  @term = term
  @idx = idx
end

Instance Method Details

#predict(maps, _fb, params) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/factbase/indexed/indexed_lt.rb', line 13

def predict(maps, _fb, params)
  return nil if @idx.nil?
  return unless @term.operands.first.is_a?(Symbol) && _scalar?(@term.operands[1])
  prop = @term.operands.first.to_s
  cache_key = [maps.object_id, @term.operands.first, :sorted]
  entry = @idx[cache_key]
  maps_array = maps.to_a
  if entry.nil?
    entry = { sorted: [], indexed_count: 0 }
    @idx[cache_key] = entry
  end
  if entry[:indexed_count] < maps_array.size
    new_pairs = []
    maps_array[entry[:indexed_count]..].each do |m|
      values = m[prop]
      next if values.nil?
      values.each do |v|
        new_pairs << [v, m]
      end
    end
    unless new_pairs.empty?
      entry[:sorted].concat(new_pairs)
      entry[:sorted].sort_by! { |pair| pair[0] }
    end
    entry[:indexed_count] = maps_array.size
  end

  threshold = @term.operands[1].is_a?(Symbol) ? params[@term.operands[1].to_s]&.first : @term.operands[1]
  return nil if threshold.nil?
  i = entry[:sorted].bsearch_index { |pair| pair[0] >= threshold } || entry[:sorted].size
  result = entry[:sorted][0...i].map { |pair| pair[1] }.uniq
  (maps & []) | result
end