Module: Factbase::Aggregates

Included in:
Term
Defined in:
lib/factbase/terms/aggregates.rb

Overview

Aggregating terms.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Instance Method Details

#_best(maps) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/factbase/terms/aggregates.rb', line 72

def _best(maps)
  k = @operands[0]
  raise "A symbol is expected, but #{k} provided" unless k.is_a?(Symbol)
  best = nil
  maps.each do |m|
    vv = m[k.to_s]
    next if vv.nil?
    vv = [vv] unless vv.respond_to?(:to_a)
    vv.each do |v|
      best = v if best.nil? || yield(v, best)
    end
  end
  best
end

#agg(fact, maps, fb) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/factbase/terms/aggregates.rb', line 50

def agg(fact, maps, fb)
  assert_args(2)
  selector = @operands[0]
  raise "A term is expected, but '#{selector}' provided" unless selector.is_a?(Factbase::Term)
  term = @operands[1]
  raise "A term is expected, but '#{term}' provided" unless term.is_a?(Factbase::Term)
  subset = fb.query(selector, maps).each(fb, fact).to_a
  term.evaluate(nil, subset, fb)
end

#empty(fact, maps, fb) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/factbase/terms/aggregates.rb', line 60

def empty(fact, maps, fb)
  assert_args(1)
  term = @operands[0]
  raise "A term is expected, but '#{term}' provided" unless term.is_a?(Factbase::Term)
  # rubocop:disable Lint/UnreachableLoop
  fb.query(term, maps).each(fb, fact) do
    return false
  end
  # rubocop:enable Lint/UnreachableLoop
  true
end

#max(_fact, maps, _fb) ⇒ Object



19
20
21
22
# File 'lib/factbase/terms/aggregates.rb', line 19

def max(_fact, maps, _fb)
  assert_args(1)
  _best(maps) { |v, b| v > b }
end

#min(_fact, maps, _fb) ⇒ Object



14
15
16
17
# File 'lib/factbase/terms/aggregates.rb', line 14

def min(_fact, maps, _fb)
  assert_args(1)
  _best(maps) { |v, b| v < b }
end

#nth(_fact, maps, _fb) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/factbase/terms/aggregates.rb', line 24

def nth(_fact, maps, _fb)
  assert_args(2)
  pos = @operands[0]
  raise "An integer is expected, but #{pos} provided" unless pos.is_a?(Integer)
  k = @operands[1]
  raise "A symbol is expected, but #{k} provided" unless k.is_a?(Symbol)
  m = maps[pos]
  return nil if m.nil?
  m[k.to_s]
end

#sum(_fact, maps, _fb) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/factbase/terms/aggregates.rb', line 35

def sum(_fact, maps, _fb)
  k = @operands[0]
  raise "A symbol is expected, but '#{k}' provided" unless k.is_a?(Symbol)
  sum = 0
  maps.each do |m|
    vv = m[k.to_s]
    next if vv.nil?
    vv = [vv] unless vv.respond_to?(:to_a)
    vv.each do |v|
      sum += v
    end
  end
  sum
end