Class: ShuntingYard
- Inherits:
-
Object
- Object
- ShuntingYard
- Defined in:
- lib/lamep/shunting_yard.rb
Instance Method Summary collapse
- #burn_stack_to_higher_precedence(token) ⇒ Object
-
#initialize(tokens) ⇒ ShuntingYard
constructor
A new instance of ShuntingYard.
- #postfix ⇒ Object
Constructor Details
#initialize(tokens) ⇒ ShuntingYard
Returns a new instance of ShuntingYard.
3 4 5 6 |
# File 'lib/lamep/shunting_yard.rb', line 3 def initialize(tokens) fail ArgumentError.new("Expected array: Got #{tokens.class}") unless tokens.is_a?(Array) @tokens = tokens end |
Instance Method Details
#burn_stack_to_higher_precedence(token) ⇒ Object
35 36 37 38 39 |
# File 'lib/lamep/shunting_yard.rb', line 35 def burn_stack_to_higher_precedence(token) until @stack.empty? || @stack.last == '(' || Operator.precedence!(token) < Operator.precedence!(@stack.last) @output << @stack.pop end end |
#postfix ⇒ 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 |
# File 'lib/lamep/shunting_yard.rb', line 8 def postfix @output = [] @stack = [] bracket_sum = 0 @tokens.each do |token| case token when '(' bracket_sum += 1 @stack << token when ')' bracket_sum -= 1 fail('Right parentheses mismatch') if bracket_sum < 0 burn_stack_to_parentheses else if Operator.exists?(token) burn_stack_to_higher_precedence(token) @stack << token else @output << token end end end fail('Left parentheses mismatch') if bracket_sum > 0 @output += @stack.reverse @output end |