Skip to content
Oeiuwq Faith Blog OpenSource Porfolio

danielberkompas/destructure

Javascript-style destructuring for Elixir

danielberkompas/destructure.json
{
"createdAt": "2016-10-31T21:04:47Z",
"defaultBranch": "master",
"description": "Javascript-style destructuring for Elixir",
"fullName": "danielberkompas/destructure",
"homepage": null,
"language": "Elixir",
"name": "destructure",
"pushedAt": "2022-08-31T20:08:49Z",
"stargazersCount": 110,
"topics": [
"elixir",
"hex"
],
"updatedAt": "2024-06-18T02:33:23Z",
"url": "https://github.com/danielberkompas/destructure"
}

Hex.pm Build Status

Adds Javascript-style destructuring to Elixir. When working with a map, instead of writing match operation like this:

def full_name(%{first_name: first_name, last_name: last_name}) do
"#{first_name} #{last_name}"
end

You can write:

import Destructure
def full_name(d%{first_name, last_name}) do
"#{first_name} #{last_name}"
end

It also works with structs and keyword.

import Destructure
def full_name(d%Person{first_name, last_name}) do
"#{first_name} #{last_name}"
end
def full_name(d[first_name, last_name]) do
"#{first_name} #{last_name}"
end

You can also do it in a case statement.

case post(url, data) do
{:ok, d%{body}} -> # instead of {:ok, %{body: body}}
# use body variable
_other ->
# ...
end

Unlike Javascript, you can still bind custom variables:

d(%{first, last, email: mail}) = %{...}

See the Hex Documentation for more details.

Add destructure to your list of dependencies in mix.exs:

def deps do
[{:destructure, "~> 0.2.3"}]
end