Skip to content

Commit 5a94604

Browse files
committed
#55 implement remove_item_from_list/2
1 parent f67765e commit 5a94604

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/useful.ex

+12
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,18 @@ defmodule Useful do
129129
end
130130
end
131131

132+
@doc """
133+
`remove_item_from_list/2` removes a given `item` from a `list` in any position.
134+
"""
135+
def remove_item_from_list(item, list) do
136+
if Enum.member?(list, item) do
137+
i = Enum.find_index(list, fn it -> it == item end)
138+
List.delete_at(list, i)
139+
else
140+
list
141+
end
142+
end
143+
132144
@doc """
133145
`stringy_map/1` converts a `Map` of any depth/nesting into a string.
134146
Deeply nested maps are denoted by "__" (double underscore). See flatten_map/1

test/useful_test.exs

+26
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,32 @@ defmodule UsefulTest do
186186
end
187187
end
188188

189+
describe "remove_item_from_list/2" do
190+
test "remove_item_from_list/2 removes a numeric item from a list" do
191+
list = [1, 2, 3, 4]
192+
# tl/1 = "tail of list" hexdocs.pm/elixir/1.15.5/Kernel.html#tl/1
193+
assert Useful.remove_item_from_list(1, list) == tl(list)
194+
end
195+
196+
test "remove_item_from_list/2 removes a numeric item in any position" do
197+
list = [1, 2, 3, 4]
198+
updated_list = [1, 2, 4]
199+
assert Useful.remove_item_from_list(3, list) == updated_list
200+
end
201+
202+
test "remove_item_from_list/2 removes an item from the list" do
203+
list = ["don't", "panic", "about", "climate", "change"]
204+
# tl/1 = "tail of list" hexdocs.pm/elixir/1.15.5/Kernel.html#tl/1
205+
assert Useful.remove_item_from_list("don't", list) == tl(list)
206+
end
207+
208+
test "attempt to remove_item_from_list/2 ignores item *not* in list" do
209+
item = "save"
210+
list = ["AI", "will", "destroy", "us"]
211+
assert Useful.remove_item_from_list(item, list) == list
212+
end
213+
end
214+
189215
describe "stringfy_map/1" do
190216
test "returns nil string when map is nil" do
191217
assert Useful.stringify_map(nil) == "nil"

0 commit comments

Comments
 (0)