Skip to content

Commit

Permalink
remove item from heap
Browse files Browse the repository at this point in the history
  • Loading branch information
ayrat555 committed May 21, 2017
1 parent 5ae8e0f commit 6f745f5
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/rock/struct/heap.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ defmodule Rock.Struct.Heap do
%Heap{cluster_uuid: uuid, items: items}
end

def remove_item(%Heap{items: items, cluster_uuid: cluster_uuid}, uuid) do
new_items = items |> _remove_item(items, uuid)

%Heap{cluster_uuid: cluster_uuid, items: new_items}
end

defp _remove_item(items, [{_, _, cluster_uuid} = item | _], uuid) when cluster_uuid == uuid do
items |> List.delete(item)
end

defp _remove_item(_, [_, []], uuid) do
raise ArgumentError, message: "heap does not have the item with uuid #{uuid}"
end

defp _remove_item(items, [_item | tail], uuid) do
items |> _remove_item(tail, uuid)
end

defp prepare_items(cluster, clusters, link_matrix, theta) do
clusters
|> calculate_items(cluster, link_matrix, theta)
Expand Down
15 changes: 15 additions & 0 deletions test/rock/struct/heap_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ defmodule Rock.Struct.HeapTest do
alias Rock.Struct.Point
alias Rock.Struct.Heap
alias Rock.Struct.Cluster
alias Rock.Test.TestFactory

test "initializes heap" do
points = [
Expand Down Expand Up @@ -60,5 +61,19 @@ defmodule Rock.Struct.HeapTest do
end)
end)
end

test "deletes item from heap" do
items = [
{10, 15, UUID.uuid4},
item = {9, 14, uuid = UUID.uuid4},
{6, 12, UUID.uuid4},
{5, 10, UUID. uuid4}
]
heap = TestFactory.create(:heap, items)

%Heap{items: new_items} = heap |> Heap.remove_item(uuid)

refute new_items |> Enum.member?(item)
end
end

5 changes: 5 additions & 0 deletions test/support/test_factory.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule Rock.Test.TestFactory do
alias Rock.Struct.Point
alias Rock.Struct.Cluster
alias Rock.Struct.Heap

def from_string(:cluster, string_points) do
string_points
Expand All @@ -13,4 +14,8 @@ defmodule Rock.Test.TestFactory do
def from_string(:point, string_attributes) do
string_attributes |> Point.new
end

def create(:heap, items) do
%Heap{cluster_uuid: UUID.uuid4, items: items}
end
end

0 comments on commit 6f745f5

Please sign in to comment.