Skip to content

Instantly share code, notes, and snippets.

@sb8244
Created June 10, 2026 17:06
Show Gist options
  • Select an option

  • Save sb8244/4c5680c7b58ea33f03d16541942b7d2d to your computer and use it in GitHub Desktop.

Select an option

Save sb8244/4c5680c7b58ea33f03d16541942b7d2d to your computer and use it in GitHub Desktop.
defmodule ReplaceMapValues do
def call(obj, opts = [replace_fn: _]), do: iterate(obj, opts)
defp iterate(maybe_struct = %{}, opts = [replace_fn: func]) do
enumerable =
case maybe_struct do
struct = %_{} -> Map.from_struct(struct)
map = %{} -> map
end
# Preserve the original structure, but must iterate over it as a map due to Enumerable
new_value =
Enum.reduce(enumerable, maybe_struct, fn {k, v}, acc ->
Map.put(acc, k, iterate(v, opts))
end)
func.(new_value)
end
defp iterate([head | rest], opts) do
[iterate(head, opts) | iterate(rest, opts)]
end
defp iterate(primitive, replace_fn: func) do
func.(primitive)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment