Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
28 changes: 28 additions & 0 deletions lib/lazy_html/tree.ex
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,34 @@ defmodule LazyHTML.Tree do
@doc """
Performs a depth-first, post-order traversal of the given tree.

This function traverses the tree without modifying it, check `postwalk/2` and
`postwalk/3` if you need to modify the tree.
"""
@spec postreduce(
t(),
acc,
(html_node(), acc -> acc)
) :: acc
when acc: term()
def postreduce([], acc, _fun), do: acc
Comment thread
ypconstante marked this conversation as resolved.

def postreduce([node | rest], acc, fun) do
acc = postreduce(node, acc, fun)
postreduce(rest, acc, fun)
end

def postreduce({tag, attrs, children}, acc, fun) do
acc = postreduce(children, acc, fun)
fun.({tag, attrs, children}, acc)
end

def postreduce(node, acc, fun) do
fun.(node, acc)
end

@doc """
Performs a depth-first, post-order traversal of the given tree.

The mapper `fun` can return a list of nodes to replace the given
node. In order to remove a node, return an empty list.
"""
Expand Down
27 changes: 27 additions & 0 deletions test/lazy_html/tree_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,33 @@ defmodule LazyHTML.TreeTest do
end
end

describe "postreduce/3" do
test "does post-order traversal of the nodes and accumulates results" do
tree = [
{:comment, "Hello world"},
{"div", [{"class", "root"}],
[
{"span", [], ["Hello"]},
{:comment, "intersection"},
{"span", [], ["world"]}
]}
]

nodes = LazyHTML.Tree.postreduce(tree, [], fn node, acc -> [node | acc] end)

assert nodes == [
{"div", [{"class", "root"}],
[{"span", [], ["Hello"]}, {:comment, "intersection"}, {"span", [], ["world"]}]},
{"span", [], ["world"]},
"world",
{:comment, "intersection"},
{"span", [], ["Hello"]},
"Hello",
{:comment, "Hello world"}
]
end
end

describe "postwalk/3" do
test "does post-order traversal of the nodes and accumulates results" do
tree = [
Expand Down