Module: CommandSearch::Optimizer

Defined in:
lib/command_search/optimizer.rb

Class Method Summary collapse

Class Method Details

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



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

def denest!(ast, parent_type = :and)
  ast.map! do |node|
    type = node[:type]
    next node unless type == :and || type == :or || type == :not
    denest!(node[:value], type)
    next [] if node[:value] == []
    if type == :not
      only_child = node[:value].count == 1
      child = node[:value].first
      next child[:value] if only_child && child[:type] == :not
      next node
    end
    next node[:value] if node[:value].count == 1
    next node[:value] if type == parent_type
    next node[:value] if type == :and && parent_type == :not
    next node if type == :and
    denest!(node[:value], type) # type == :or, parent_type == :and
    node[:value].uniq!
    next node[:value] if node[:value].count == 1
    node
  end
  ast.flatten!
end

.optimize!(ast) ⇒ Object



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

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