From 73071848135475ee1563eb64a0820354a926d4ba Mon Sep 17 00:00:00 2001 From: nelsonic Date: Wed, 4 Oct 2023 14:35:28 +0100 Subject: [PATCH] bump package version 1.13.1 -> 1.14.0 to release list_tuple_to_unique_keys/1 function #59 --- lib/useful.ex | 49 ++++++++++++++++++++++++------------------------- mix.exs | 2 +- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/lib/useful.ex b/lib/useful.ex index 1cbc6ec..258a467 100644 --- a/lib/useful.ex +++ b/lib/useful.ex @@ -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. @@ -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 diff --git a/mix.exs b/mix.exs index 8825afd..fe47199 100644 --- a/mix.exs +++ b/mix.exs @@ -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(),