File: subexpression.rb

package info (click to toggle)
ruby-jmespath 1.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 232 kB
  • sloc: ruby: 2,039; makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,377 bytes parent folder | download
1
2
3
4
5
6
7
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
57
58
59
60
61
62
63
64
# frozen_string_literal: true
module JMESPath
  # @api private
  module Nodes
    class Subexpression < Node
      def initialize(left, right)
        @left = left
        @right = right
      end

      def visit(value)
        @right.visit(@left.visit(value))
      end

      def optimize
        Chain.new(flatten).optimize
      end

      protected

      attr_reader :left, :right

      def flatten
        nodes = [@left, @right]
        until nodes.none? { |node| node.is_a?(Subexpression) }
          nodes = nodes.flat_map do |node|
            if node.is_a?(Subexpression)
              [node.left, node.right]
            else
              [node]
            end
          end
        end
        nodes.map(&:optimize)
      end
    end

    class Chain
      def initialize(children)
        @children = children
      end

      def visit(value)
        @children.reduce(value) do |v, child|
          child.visit(v)
        end
      end

      def optimize
        children = @children.map(&:optimize)
        index = 0
        while index < children.size - 1
          if children[index].chains_with?(children[index + 1])
            children[index] = children[index].chain(children[index + 1])
            children.delete_at(index + 1)
          else
            index += 1
          end
        end
        Chain.new(children)
      end
    end
  end
end