Created
June 10, 2026 17:06
-
-
Save sb8244/4c5680c7b58ea33f03d16541942b7d2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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