Skip to content

Commit

Permalink
add make_unique_keys/1
Browse files Browse the repository at this point in the history
  • Loading branch information
ndrean committed Oct 4, 2023
1 parent ab333fc commit d4f1dc8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/useful.ex
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,30 @@ defmodule Useful do
def typeof(x) when unquote(:"is_#{type}")(x), do: unquote(type)
end

@doc """
`make_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"}]
"""

def make_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)
end

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

test "make_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"}]
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 d4f1dc8

Please sign in to comment.