Sha256: 9a76af570be569a7fc8c1de3a79e120c0c0a467bebc6e28b41100666bae501c8

Contents?: true

Size: 1.23 KB

Versions: 4

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

class Code
  class Node
    class While < Node
      WHILE_KEYWORD = "while"
      UNTIL_KEYWORD = "until"
      LOOP_KEYWORD = "loop"

      def initialize(parsed)
        return if parsed.blank?
        @operator = parsed.delete(:operator).presence
        if parsed.key?(:statement)
          @statement = Statement.new(parsed.delete(:statement))
        end
        @body = Code.new(parsed.delete(:body).presence)
      end

      def evaluate(**args)
        case @operator
        when WHILE_KEYWORD
          last = Object::Nothing.new

          while (@statement&.evaluate(**args) || Object::Nothing.new).truthy?
            last = @body&.evaluate(**args) || Object::Nothing.new
          end

          last
        when UNTIL_KEYWORD
          last = Object::Nothing.new

          while (@statement&.evaluate(**args) || Object::Nothing.new).falsy?
            last = @body&.evaluate(**args) || Object::Nothing.new
          end

          last
        when LOOP_KEYWORD
          loop { @body&.evaluate(**args) || Object::Nothing.new }
          Object::Nothing.new
        else
          Object::Nothing.new
        end
      rescue Error::Break => e
        e.value || Object::Nothing.new
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
code-ruby-0.13.1 lib/code/node/while.rb
code-ruby-0.13.0 lib/code/node/while.rb
code-ruby-0.12.0 lib/code/node/while.rb
code-ruby-0.11.0 lib/code/node/while.rb