Skip to content

Commit

Permalink
Optimize Floki.children (#533)
Browse files Browse the repository at this point in the history
  • Loading branch information
ypconstante committed Feb 9, 2024
1 parent c2c1a25 commit 712c08a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 17 deletions.
20 changes: 11 additions & 9 deletions lib/floki.ex
Original file line number Diff line number Diff line change
Expand Up @@ -606,19 +606,21 @@ defmodule Floki do
"""

@spec children(html_node(), Keyword.t()) :: html_tree() | nil
def children(html_node, opts \\ [include_text: true])

def children(html_node, opts \\ [include_text: true]) do
case html_node do
{_, _, subtree} ->
filter_children(subtree, opts[:include_text])
def children({_, _, subtree}, include_text: false) do
Enum.filter(subtree, &is_tuple/1)
end

_ ->
nil
end
def children({_, _, subtree}, include_text: _) do
subtree
end

def children({_, _, _} = html_node, opts) do
children(html_node, include_text: opts[:include_text])
end

defp filter_children(children, false), do: Enum.filter(children, &is_tuple(&1))
defp filter_children(children, _), do: children
def children(_html_node, _opts), do: nil

@doc """
Returns a list with attribute values for a given selector.
Expand Down
28 changes: 20 additions & 8 deletions test/floki_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1587,10 +1587,17 @@ defmodule FlokiTest do
# Floki.children/2

test "returns the children elements of an element including the text" do
assert Floki.children({"div", [], ["a parent", {"span", [], ["a child"]}]}) == [
"a parent",
{"span", [], ["a child"]}
]
html_node = {"div", [], ["a parent", {"span", [], ["a child"]}]}

expected = [
"a parent",
{"span", [], ["a child"]}
]

assert Floki.children(html_node) == expected
assert Floki.children(html_node, include_text: true) == expected
assert Floki.children(html_node, include_text: true, unknown_option: true) == expected
assert Floki.children(html_node, unknown_option: true) == expected
end

test "returns the children elements of an element without the text" do
Expand All @@ -1599,14 +1606,19 @@ defmodule FlokiTest do

[elements | _] = Floki.find(html, "body > div")

assert [
{"span", [], ["child 1"]},
{"span", [], ["child 2"]}
] = Floki.children(elements, include_text: false)
expected = [
{"span", [], ["child 1"]},
{"span", [], ["child 2"]}
]

assert Floki.children(elements, include_text: false) == expected
assert Floki.children(elements, include_text: false, unknown_option: true) == expected
end

test "returns nil if the given html is not a valid tuple" do
assert Floki.children([]) == nil
assert Floki.children([], include_text: true) == nil
assert Floki.children([], include_text: false) == nil
end

# Floki.attribute/3
Expand Down

0 comments on commit 712c08a

Please sign in to comment.