Class: ShuntingYard
- Inherits:
-
Object
- Object
- ShuntingYard
- Defined in:
- lib/lamep/shunting_yard.rb
Instance Method Summary collapse
-
#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
#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 MissingLeftParenthesesError 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 MissingRightParenthesesError if bracket_sum > 0 @output += @stack.reverse @output end |