Commit 994c5476 authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Simplify finding next comment.

Instead of searching for next comment each time, just link every comment
to the next one and then simply look up the next.
parent dc6089e1
Loading
Loading
Loading
Loading
+16 −18
Original line number Diff line number Diff line
@@ -23,26 +23,34 @@ module JsDuck
      json = @v8.eval("JSON.stringify(esprima.parse(js, {comment: true, range: true}))")
      @ast = JSON.parse(json, :max_nesting => false)

      link_comments
      locate_comments
    end

    # Establishes links between comments, so we can easily use
    # comment["next"] to get to the next comment.
    def link_comments
      @ast["comments"].each_with_index do |comment, i|
        comment["next"] = @ast["comments"][i+1]
      end
    end

    def locate_comments
      @ast["comments"].map do |comment|
        {
          :comment => comment["value"],
          :code => stuff_after(comment["range"])
          :code => stuff_after(comment)
        }
      end
    end

    # Sees if there is some code following the comment at specified
    # range.  Returns the code found.  But if the comment is instead
    # Sees if there is some code following the comment.
    # Returns the code found.  But if the comment is instead
    # followed by another comment, returns nil.
    def stuff_after(range)
      code = code_after(range)
      comment = comment_after(range)
      if code && comment
        return code["range"][0] < comment["range"][0] ? code : nil
    def stuff_after(comment)
      code = code_after(comment["range"])
      if code && comment["next"]
        return code["range"][0] < comment["next"]["range"][0] ? code : nil
      else
        code
      end
@@ -58,15 +66,5 @@ module JsDuck
      return nil
    end

    # Looks for comment following the given range
    def comment_after(range)
      @ast["comments"].each do |item|
        if range[1] < item["range"][0]
          return item
        end
      end
      return nil
    end

  end
end