Skip to content

Commit 2838669

Browse files
committed
Optimize selector traversal
Avoid extra reversals while preserving descendant order.
1 parent 9be11cf commit 2838669

1 file changed

Lines changed: 10 additions & 10 deletions

File tree

lib/floki/finder.ex

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ defmodule Floki.Finder do
319319
end
320320

321321
defp get_selector_nodes(%Selector.Combinator{match_type: :child}, html_node, _tree) do
322-
Enum.reverse(html_node.children_nodes_ids)
322+
html_node.children_nodes_ids
323323
end
324324

325325
defp get_selector_nodes(%Selector.Combinator{match_type: :adjacent_sibling}, html_node, tree) do
@@ -373,7 +373,6 @@ defmodule Floki.Finder do
373373
case get_node(node_id, tree) do
374374
%{children_nodes_ids: children} when children != [] ->
375375
do_get_descendant_ids(children, tree, [])
376-
|> Enum.reverse()
377376

378377
_ ->
379378
[]
@@ -383,16 +382,17 @@ defmodule Floki.Finder do
383382
defp do_get_descendant_ids([], _tree, acc), do: acc
384383

385384
defp do_get_descendant_ids([node_id | rest], tree, acc) do
386-
acc = do_get_descendant_ids(rest, tree, acc)
387-
acc = [node_id | acc]
385+
acc =
386+
case get_node(node_id, tree) do
387+
%{children_nodes_ids: children} when children != [] ->
388+
do_get_descendant_ids(children, tree, acc)
388389

389-
case get_node(node_id, tree) do
390-
%{children_nodes_ids: children} when children != [] ->
391-
do_get_descendant_ids(children, tree, acc)
390+
_ ->
391+
acc
392+
end
392393

393-
_ ->
394-
acc
395-
end
394+
acc = [node_id | acc]
395+
do_get_descendant_ids(rest, tree, acc)
396396
end
397397

398398
@spec map(Floki.html_tree() | Floki.html_node(), function()) ::

0 commit comments

Comments
 (0)