dwyl / dwyl/useful

List comprehension is... useful

Open
#67 2 comments 2 reactions 0 assignees View on GitHub
enhancement
Dominant language
Elixir
Stars
36
Forks
6
PR merge metrics
No merged PRs in 30d

Description

I had this pretty (useful) complicated function:

```elixir
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
```

Instead, using a comprehension list does the same job and is **easy to understand**....Never too late to improve!

```elixir
def list_tuples_to_unique_keys_from_comprehension(parts) do
for {{f, l, m}, i}<- Enum.with_index(parts) do
{f<>"-"<>Integer.to_string(i+1), l,m}
end
end
```

```elixir
parts = [
{
"files",
[
{"content-type", "image/png"},
{"content-disposition", "form-data; name=\"files\"; filename=\"first.png\""}
],
%{path: "..", content_type: "image/png", filename: "first.png"}
},
{
"files",
[
{"content-type", "image/webp"},
{"content-disposition", "form-data; name=\"files\"; filename=\"second.webp\""}
],
%{path: "...", content_type: "image/webp", filename: "second.webp"}
}
]

list_tuples_to_unique_keys_from_comprehension(parts)
[
{
"files-1",
^^^
[
{"content-type", "image/png"},
{"content-disposition", "form-data; name=\"files\"; filename=\"first.png\""}
],
%{filename: "first.png", path: "..", content_type: "image/png"}
},
{
"files-2",
^^^
[
{"content-type", "image/png"},
{"content-disposition", "form-data; name=\"files\"; filename=\"first.png\""}
],
%{filename: "first.png", path: "..", content_type: "image/png"}
}
]
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.