Module: CommandSearch::Optimizer

Defined in:
lib/command_search/optimizer.rb

Class Method Summary collapse

Class Method Details

.denest!(ast, parent_type = :paren) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/command_search/optimizer.rb', line 5

def denest!(ast, parent_type = :paren)
  ast.map! do |node|
    next [] if node[:type] == :quoted_str && node[:value] == '' && [:paren, :pipe, :minus].include?(parent_type)
    type = node[:nest_type]
    next node unless type
    next node unless type == :paren || type == :pipe || type == :minus
    denest!(node[:value], type)
    next [] if node[:value] == []
    if type == :minus
      only_child = node[:value].count == 1
      child = node[:value].first
      next child[:value] if only_child && child[:nest_type] == :minus
      next node
    end
    next node[:value] if node[:value].count == 1
    next node[:value] if type == parent_type
    next node[:value] if type == :paren && parent_type == :minus
    next node if type == :paren
    denest!(node[:value], type) # type == :pipe, parent_type == :paren
    node[:value].uniq!
    node
  end
  ast.flatten!
end

.optimize!(ast) ⇒ Object



30
31
32
33
34
# File 'lib/command_search/optimizer.rb', line 30

def optimize!(ast)
  denest!(ast)
  ast.uniq!
  ast
end