Skip to content

Instantly share code, notes, and snippets.

@josevalim
Created September 6, 2015 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josevalim/535a3db5a5a03ebfde0f to your computer and use it in GitHub Desktop.
Save josevalim/535a3db5a5a03ebfde0f to your computer and use it in GitHub Desktop.
defmodule WithName do
def with_name(name) do
fn :get_and_update, data, next ->
get_and_update(data, next, name, [], [])
end
end
defp get_and_update([%{"name" => name}=map|t], next, given_name, get_acc, update_acc) when name == given_name do
{get, update} = next.(map)
get_and_update(t, next, given_name, [get|get_acc], [update|update_acc])
end
defp get_and_update([h|t], next, name, get_acc, update_acc) do
get_and_update(t, next, name, get_acc, [h|update_acc])
end
defp get_and_update([], _next, _name, get_acc, update_acc) do
{Enum.reverse(get_acc), Enum.reverse(update_acc)}
end
end
x = %{"layers" => [%{"name" => "x"}, %{"name" => "y", "objects" => []}]}
IO.inspect update_in(x, ["layers", WithName.with_name("y"), "objects"], fn _ -> ["a"] end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment