Module: Rudash::SubsetDeepMatch

Defined in:
lib/utils/subset_deep_match.rb

Class Method Summary collapse

Class Method Details

.subset_deep_match?Boolean

Returns:

  • (Boolean)


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
# File 'lib/utils/subset_deep_match.rb', line 9

def self.subset_deep_match?
  subset_matcher = ->(slice, collection) {
    match = true

    # If was called with two arrays then the logic will be to
    # check if every "slice" items exist somehow in the collection
    # without any order consideration.
    if slice.is_a?(Array) && collection.is_a?(Array)
      return R_.every?(slice, ->(slice_val) {
        R_.some?(collection, ->(collection_val) {
          self.subset_deep_match?.call(slice_val, collection_val)
        })
      })
    end

    begin
      R_.each(collection, ->(_v) {
        R_.each(slice, ->(value, key) {
          if value.is_a?(Hash) && collection[key].is_a?(Hash)
            match &= self.subset_deep_match?.call(value, collection[key])
          elsif value.is_a?(Array) && collection[key].is_a?(Array)
            match &= self.subset_deep_match?.call(value, collection[key])
          elsif value != collection[key]
            match = false
          end
        })

        # That was done for performance manners since
        # R_.each don't stop when returning false from the lambda
        # so we force it to stop by throwing an exception that we catch later
        # It's the same hack for JavaScript forEach function.
        raise if match == false
      })
    rescue StandardError
      return false
    end

    match
  }

  subset_matcher.curry
end