Sha256: 8d5e249dd41ed677cc59910cea90a48b131fca2fe3a527e7625f74df695696d0

Contents?: true

Size: 1.79 KB

Versions: 24

Compression:

Stored size: 1.79 KB

Contents

module Ruby2JS
  class Converter

    # (case
    #   (send nil :a)
    #   (when
    #      (int 1)
    #      (...))
    #   (...))

    handle :case do |expr, *whens, other|
      begin
        inner, @inner = @inner, @ast

        has_range = whens.any? do |node| 
          node.children.any? {|child| [:irange, :erange].include? child.type}
        end

        if has_range
          # https://stackoverflow.com/questions/5619832/switch-on-ranges-of-integers-in-javascript
          puts 'switch (true) {'
        else
          put 'switch ('; parse expr; puts ') {'
        end

        whens.each_with_index do |node, index|
          puts '' unless index == 0

          *values, code = node.children

          values.each do |value| 
            put 'case '; 
            if has_range
              if value.type == :irange
                parse expr; put ' >= '; parse value.children.first; put " && "
                parse expr; put ' <= '; parse value.children.last; put ":#@ws"
              elsif value.type == :erange
                parse expr; put ' >= '; parse value.children.first; put " && "
                parse expr; put ' < '; parse value.children.last; put ":#@ws"
              else
                parse expr; put ' == '; parse value; put ":#@ws"
              end
            else
              parse value; put ":#@ws"
            end
          end

          parse code, :statement
          last = code
          while last.type == :begin
            last = last.children.last
          end

          if other or index < whens.length-1
            put "#{@sep}" 
            put "break#@sep" unless last.type == :return
          end
        end

        (put "#{@nl}default:#@ws"; parse other, :statement) if other

        sput '}'
      ensure
        @inner = inner
      end
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
ruby2js-3.6.1 lib/ruby2js/converter/case.rb
ruby2js-3.6.0 lib/ruby2js/converter/case.rb
ruby2js-3.5.3 lib/ruby2js/converter/case.rb
ruby2js-3.5.2 lib/ruby2js/converter/case.rb
ruby2js-3.5.1 lib/ruby2js/converter/case.rb
ruby2js-3.5.0 lib/ruby2js/converter/case.rb
ruby2js-3.4.0 lib/ruby2js/converter/case.rb
ruby2js-3.3.6 lib/ruby2js/converter/case.rb
ruby2js-3.3.5 lib/ruby2js/converter/case.rb
ruby2js-3.3.4 lib/ruby2js/converter/case.rb
ruby2js-3.3.3 lib/ruby2js/converter/case.rb
ruby2js-3.3.2 lib/ruby2js/converter/case.rb
ruby2js-3.3.1 lib/ruby2js/converter/case.rb
ruby2js-3.3.0 lib/ruby2js/converter/case.rb
ruby2js-3.2.0 lib/ruby2js/converter/case.rb
ruby2js-3.1.2 lib/ruby2js/converter/case.rb
ruby2js-3.1.1 lib/ruby2js/converter/case.rb
ruby2js-3.1.0 lib/ruby2js/converter/case.rb
ruby2js-3.0.15 lib/ruby2js/converter/case.rb
ruby2js-3.0.14 lib/ruby2js/converter/case.rb