equivalent8
equivalent8

Reputation: 14227

Selecting value from list of tuples Elixir

I'm trying to extract values from list of tuples:

s3_headers = %{headers: [{"x-amz-id-2","yQKurzVIApkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFBINsPxe+7Vc="},
  {"x-amz-request-id", "82xxxxxxxxx23"},
  {"Date", "Thu, 25 May 2017 22:03:09 GMT"},
  {"Last-Modified", "Thu, 25 May 2017 21:42:28 GMT"},
  {"ETag", "\"6f04733333333333333368997\""},
  {"x-amz-meta-original_name", "Screenshot from 2016-11-27 17-32-03.png"},
  {"Accept-Ranges", "bytes"}, {"Content-Type", ""},
  {"Content-Length", "612391"}, {"Server", "AmazonS3"}], status_code: 200}

The way how I manage to do it so far is like this:

{"x-amz-meta-original_name", original_name } = s3_headers |> List.keyfind("x-amz-meta-original_name", 0)
{"Content-Length", content_length }          = s3_headers |> List.keyfind("Content-Length", 0)
{"Content-Type", content_length }            = s3_headers |> List.keyfind("Content-Type", 0)

It feels like overcomplication can you recommend better way ?

Upvotes: 11

Views: 7038

Answers (1)

Steve Pallen
Steve Pallen

Reputation: 4507

I usually convert tuple lists with string keys to a Map. Then you access with string keys. This will take a little more time upfront, but much less time of each access than Enum.find

iex(19)> headers = Enum.into s3_headers[:headers], %{}
%{"Accept-Ranges" => "bytes", "Content-Length" => "612391",
  "Content-Type" => "", "Date" => "Thu, 25 May 2017 22:03:09 GMT",
  "ETag" => "\"6f04733333333333333368997\"",
  "Last-Modified" => "Thu, 25 May 2017 21:42:28 GMT", "Server" => "AmazonS3",
  "x-amz-id-2" => "yQKurzVIApkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxFBINsPxe+7Vc=",
  "x-amz-meta-original_name" => "Screenshot from 2016-11-27 17-32-03.png",
  "x-amz-request-id" => "82xxxxxxxxx23"}
iex(20)> original_name = headers["x-amz-meta-original_name"]
"Screenshot from 2016-11-27 17-32-03.png"
iex(21)> content_length = headers["Content-Length"]
"612391"

Upvotes: 21

Related Questions