Skip to content

Commit

Permalink
add list_tuples_to_unique_keys/1
Browse files Browse the repository at this point in the history
  • Loading branch information
ndrean committed Oct 4, 2023
1 parent d4f1dc8 commit 983218c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
9 changes: 5 additions & 4 deletions lib/useful.ex
Original file line number Diff line number Diff line change
Expand Up @@ -287,18 +287,18 @@ defmodule Useful do
end

@doc """
`make_unique_keys/1` turns a list of tuples with the same key into a list of tuples with a unique key.
`list_tuples_to_unique_keys/1` turns a list of tuples with the same key into a list of tuples with a unique key.
Useful when you deal with "multipart".
## Example
iex> parts = [{"file", "header", "pic1.png"}, {"file", "header", "pic2.png"}]
iex> Useful.make_unique_keys(parts)
[{"file-2", "header", "pic2.png"}, {"file-1", "header", "pic1.png"}]
iex> Useful.list_tuples_to_unique_keys(parts)
[{"file-1", "header", "pic1.png"}, {"file-2", "header", "pic2.png"}]
"""

def make_unique_keys(parts) do
def list_tuples_to_unique_keys(parts) do
key = parts |> hd() |> elem(0)
new_keys = Enum.map(1..length(parts), &(key <> "-#{&1}"))

Expand All @@ -308,6 +308,7 @@ defmodule Useful do
| acc
]
end)
|> Enum.sort()
end

# No idea how to test this. Do you? ¯\_(ツ)_/¯
Expand Down
7 changes: 3 additions & 4 deletions test/useful_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ defmodule UsefulTest do
use Plug.Test
doctest Useful

test "make_unique_keys/1 makes unique keys" do
test "list_tuples_to_unique_keys/1 makes unique keys" do
parts = [{"file", 1, "a"}, {"file", 2, "b"}, {"file", 3, "c"}]

assert Useful.make_unique_keys(parts) |> Enum.sort() ==
[{"file-1", 1, "a"}, {"file-2", 2, "b"}, {"file-3", 3, "c"}]
expected = [{"file-1", 1, "a"}, {"file-2", 2, "b"}, {"file-3", 3, "c"}]
assert Useful.list_tuples_to_unique_keys(parts) == expected
end

test "atomize_map_keys/1 converts string keys to map" do
Expand Down

0 comments on commit 983218c

Please sign in to comment.