Sha256: eb34e1deeff26174ba74598985692f98e4b492ed9f7f4b1e59f49f2bedbd70f9

Contents?: true

Size: 1.19 KB

Versions: 4

Compression:

Stored size: 1.19 KB

Contents

require 'opal/nodes/base'

module Opal
  module Nodes
    class IfNode < Base
      handle :if

      children :test, :true_body, :false_body

      def compile
        truthy, falsy = self.truthy, self.falsy

        push "if ("

        # optimize unless (we don't want a else() unless we need to)
        if falsy and !truthy
          truthy = falsy
          falsy = nil
          push js_falsy(test)
        else
          push js_truthy(test)
        end

        push ") {"

        # skip if-body if no truthy sexp
        indent { line stmt(truthy) } if truthy

        if falsy
          if falsy.type == :if
            line "} else ", stmt(falsy)
          else
            indent do
              line "} else {"
              line stmt(falsy)
            end

            line "}"
          end
        else
          push "}"
        end

        wrap "(function() {", "; return nil; })()" if needs_wrapper?
      end

      def truthy
        needs_wrapper? ? compiler.returns(true_body || s(:nil)) : true_body
      end

      def falsy
        needs_wrapper? ? compiler.returns(false_body || s(:nil)) : false_body
      end

      def needs_wrapper?
        expr? or recv?
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
opal-0.5.5 lib/opal/nodes/if.rb
opal-0.5.4 lib/opal/nodes/if.rb
opal-0.5.2 lib/opal/nodes/if.rb
opal-0.5.0 lib/opal/nodes/if.rb