Module: DecisionAgent::Dsl::Operators::CollectionOperators

Defined in:
lib/decision_agent/dsl/operators/collection_operators.rb

Overview

Handles collection operators: contains_all, contains_any, intersects, subset_of

Class Method Summary collapse

Class Method Details

.handle(op, actual_value, expected_value) ⇒ Object



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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/decision_agent/dsl/operators/collection_operators.rb', line 8

def self.handle(op, actual_value, expected_value)
  case op
  when "contains_all"
    # Checks if array contains all specified elements
    return false unless actual_value.is_a?(Array)
    return false unless expected_value.is_a?(Array)
    return true if expected_value.empty?

    # OPTIMIZE: Use Set for O(1) lookups instead of O(n) include?
    actual_set = actual_value.to_set
    expected_value.all? { |item| actual_set.include?(item) }

  when "contains_any"
    # Checks if array contains any of the specified elements
    return false unless actual_value.is_a?(Array)
    return false unless expected_value.is_a?(Array)
    return false if expected_value.empty?

    # OPTIMIZE: Use Set for O(1) lookups instead of O(n) include?
    actual_set = actual_value.to_set
    expected_value.any? { |item| actual_set.include?(item) }

  when "intersects"
    # Checks if two arrays have any common elements
    return false unless actual_value.is_a?(Array)
    return false unless expected_value.is_a?(Array)
    return false if actual_value.empty? || expected_value.empty?

    # OPTIMIZE: Use Set intersection for O(n) instead of array & which creates intermediate array
    if actual_value.size <= expected_value.size
      expected_set = expected_value.to_set
      actual_value.any? { |item| expected_set.include?(item) }
    else
      actual_set = actual_value.to_set
      expected_value.any? { |item| actual_set.include?(item) }
    end

  when "subset_of"
    # Checks if array is a subset of another array
    return false unless actual_value.is_a?(Array)
    return false unless expected_value.is_a?(Array)
    return true if actual_value.empty?

    # OPTIMIZE: Use Set for O(1) lookups instead of O(n) include?
    expected_set = expected_value.to_set
    actual_value.all? { |item| expected_set.include?(item) }
  end
  # Returns nil if not handled by this module
end