Skip to content

Commit

Permalink
fix tests add find_by_id method
Browse files Browse the repository at this point in the history
  • Loading branch information
vacarsu committed Sep 22, 2023
1 parent 08026b5 commit ea15f17
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
16 changes: 13 additions & 3 deletions lib/scenic/graph.ex
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,6 @@ defmodule Scenic.Graph do
"""

@spec find(graph :: t(), (any -> as_boolean(term()))) :: list(Primitive.t())
def find(graph, finder)

def find(%__MODULE__{} = graph, finder) do
reduce(graph, [], fn p, acc ->
p
Expand All @@ -597,6 +595,18 @@ defmodule Scenic.Graph do
|> Enum.reverse()
end

def find_by_id(%__MODULE__{} = graph, finder) do
reduce(graph, [], fn p, acc ->
Map.get(p, :id)
|> finder.()
|> case do
true -> [p | acc]
false -> acc
end
end)
|> Enum.reverse()
end

# --------------------------------------------------------
# transform a single primitive by uid
# pass in a list of uids to transform
Expand Down Expand Up @@ -651,7 +661,7 @@ defmodule Scenic.Graph do
# pass in a finder function
def modify(%__MODULE__{} = graph, finder, action) when is_function(finder, 1) do
graph
|> find(finder)
|> find_by_id(finder)
|> Enum.map(fn %{id: id} -> id end)
|> Enum.uniq()
|> Enum.reduce(graph, &modify(&2, &1, action))
Expand Down
24 changes: 21 additions & 3 deletions test/scenic/graph_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -267,20 +267,38 @@ defmodule Scenic.GraphTest do
end

# ============================================================================
test "find returns the matching items" do
test "find returns the matching items" do
graph =
Graph.build()
|> Text.add_to_graph("text one", id: {:a, :one})
|> Text.add_to_graph("text two", id: {:a, :two})
|> Text.add_to_graph("text three", id: {:b, :three})

# confirm result
assert Graph.find(graph, &match?({:a, :one}, &1.id)) == [
Graph.get!(graph, {:a, :one})
]

assert Graph.find(graph, &match?({:b, :three}, &1.id)) == [
Graph.get!(graph, {:b, :three})
]
end

# ============================================================================
test "find_by_id returns the matching items" do
graph =
Graph.build()
|> Text.add_to_graph("text one", id: {:a, :one})
|> Text.add_to_graph("text two", id: {:a, :two})
|> Text.add_to_graph("text three", id: {:b, :three})

# confirm result
assert Graph.find(graph, &match?({:a, _}, &1)) == [
assert Graph.find_by_id(graph, &match?({:a, _}, &1)) == [
Graph.get!(graph, {:a, :one}),
Graph.get!(graph, {:a, :two})
]

assert Graph.find(graph, &match?({:b, _}, &1)) == [
assert Graph.find_by_id(graph, &match?({:b, _}, &1)) == [
Graph.get!(graph, {:b, :three})
]
end
Expand Down

0 comments on commit ea15f17

Please sign in to comment.