Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize leftpad on raw_html #526

Merged
merged 3 commits into from
Jan 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions lib/floki/raw_html.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ defmodule Floki.RawHTML do

padding =
case Keyword.fetch(options, :pretty) do
{:ok, true} -> %{pad: " ", line_ending: "\n", depth: 0}
{:ok, true} -> %{pad: "", pad_increase: " ", line_ending: "\n", depth: 0}
_ -> :noop
end

Expand Down Expand Up @@ -178,10 +178,16 @@ defmodule Floki.RawHTML do
_ -> encoder
end

children_content =
case children do
[] -> ""
_ -> build_raw_html(children, "", encoder, pad_increase(padding), self_closing_tags)
end

[
tag_with_attrs(type, attrs, children, padding, encoder, self_closing_tags),
line_ending(padding),
build_raw_html(children, "", encoder, pad_increase(padding), self_closing_tags),
children_content,
close_end_tag(type, children, padding, self_closing_tags)
]
end
Expand Down Expand Up @@ -211,7 +217,7 @@ defmodule Floki.RawHTML do
do: map_intersperse(Map.to_list(attrs), separator, mapper)

defp leftpad(:noop), do: ""
defp leftpad(%{pad: pad, depth: depth}), do: String.duplicate(pad, depth)
defp leftpad(%{pad: pad}), do: pad

defp leftpad_content(:noop, string), do: string

Expand All @@ -226,7 +232,11 @@ defmodule Floki.RawHTML do
end

defp pad_increase(:noop), do: :noop
defp pad_increase(padder = %{depth: depth}), do: %{padder | depth: depth + 1}

defp pad_increase(padder = %{depth: depth, pad_increase: pad_increase}) do
depth = depth + 1
%{padder | depth: depth, pad: String.duplicate(pad_increase, depth)}
end

defp line_ending(:noop), do: ""
defp line_ending(%{line_ending: line_ending}), do: line_ending
Expand Down