Skip to content

Commit

Permalink
bump package version 1.13.1 -> 1.14.0 to release list_tuple_to_unique…
Browse files Browse the repository at this point in the history
…_keys/1 function #59
  • Loading branch information
nelsonic committed Oct 4, 2023
1 parent 1dce25e commit 7307184
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 26 deletions.
49 changes: 24 additions & 25 deletions lib/useful.ex
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,30 @@ defmodule Useful do
end
end

@doc """
`list_tuples_to_unique_keys/1` turns a list of tuples
with the same key into a list of tuples with unique keys.
Useful when dealing with "multipart" forms that upload multiple files.
## 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

@doc """
`remove_item_from_list/2` removes a given `item` from a `list` in any position.
Expand Down Expand Up @@ -286,31 +310,6 @@ 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
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ defmodule Useful.MixProject do
[
app: :useful,
description: "A collection of useful functions",
version: "1.13.1",
version: "1.14.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps(),
Expand Down

0 comments on commit 7307184

Please sign in to comment.