MapTransform (map_transform v0.1.2)

This is a simple library that can transform one map into another through mapping rules.

Summary

Functions

Transform one map into another.

Types

mapping()

@type mapping() :: {path(), path()} | {path(), path(), (term() -> term())}

path()

@type path() :: [term(), ...]

Functions

transform(source, mapping)

@spec transform(map(), [mapping()]) :: map()

Transform one map into another.

Format for mappings

For the paths is the standard that get_in/2 and put_in/2 use. For example to get data from c in %{a: %{b: %{c: 1}}} you would provide [:a, :b, :c] as the path.

Then we'll use these paths in the mapping in a list of tuples where:

{from_path, to_path}
{from_path, to_path, &transform_function/1}

Example

Basic

iex> mapping = [
...>   {[:a, :b, :c], [:abc]}
...> ]
...> source = %{a: %{b: %{c: 1}}}
...> transform(source, mapping)
%{abc: 1}

String keys and using a transform function

iex> mapping = [
...>   {["a", "b", "c"], [:abc], &String.to_integer/1}
...> ]
...> source = %{"a" => %{"b" => %{"c" => "1"}}}
...> transform(source, mapping)
%{abc: 1}

Any nesting

iex> mapping = [
...>   {[:a, :b, :c], [:foo, :bar]}
...> ]
...> source = %{a: %{b: %{c: 1}}}
...> transform(source, mapping)
%{foo: %{bar: 1}}