Skip to content

Commit

Permalink
Merge pull request #61 from ndrean/unique-tuple
Browse files Browse the repository at this point in the history
added list_tuple_to_unique_keys/1
  • Loading branch information
nelsonic committed Oct 4, 2023
2 parents ab333fc + 0b0fd4d commit 3ad62d0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/useful.ex
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,31 @@ defmodule Useful do
def typeof(x) when unquote(:"is_#{type}")(x), do: unquote(type)
end

@doc """
`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.list_tuples_to_unique_keys(parts)
[{"file-1", "header", "pic1.png"}, {"file-2", "header", "pic2.png"}]
"""

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

Enum.zip_reduce([parts, new_keys], [], fn [elt, new_key], acc ->
[
elt |> Tuple.delete_at(0) |> Tuple.insert_at(0, new_key)
| acc
]
end)
|> Enum.sort()
end

# No idea how to test this. Do you? ¯\_(ツ)_/¯
# coveralls-ignore-start
def typeof(_) do
Expand Down
6 changes: 6 additions & 0 deletions test/useful_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ defmodule UsefulTest do
use Plug.Test
doctest Useful

test "list_tuples_to_unique_keys/1 makes unique keys" do
parts = [{"file", 1, "a"}, {"file", 2, "b"}, {"file", 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
map = %{"name" => "alex", id: 1}
# IO.inspect(map, label: "map")
Expand Down

0 comments on commit 3ad62d0

Please sign in to comment.