From 924cdb6f666509107eca0eab4f326c33dfb49063 Mon Sep 17 00:00:00 2001 From: Zachary Berkompas Date: Mon, 5 Feb 2018 09:26:00 -0800 Subject: [PATCH 1/3] Handle non-map or non-nil values --- lib/maybe.ex | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/maybe.ex b/lib/maybe.ex index 85e3041..61c8fb5 100644 --- a/lib/maybe.ex +++ b/lib/maybe.ex @@ -1,6 +1,6 @@ defmodule Maybe do @moduledoc """ - Access nested maps and structs, protected from `nil`. + Access nested maps and structs, protected from `nil`. See `maybe/1` or `maybe/2` for more details. @@ -16,7 +16,7 @@ defmodule Maybe do """ @doc """ - Get a value out of a nested map or struct, or return nil. + Get a value out of a nested map or struct, or return nil. Compiles down to `maybe/2`. In other words, this: @@ -35,6 +35,10 @@ defmodule Maybe do iex> map = %{city: nil} ...> maybe(map.city.name) nil + + iex> map = %{city: :unknown} + ...> maybe(map.city.name) + nil """ defmacro maybe(ast) do [variable | keys] = extract_keys(ast) @@ -45,7 +49,7 @@ defmodule Maybe do end @doc """ - Get a value out of a nested map or struct, or return nil. + Get a value out of a nested map or struct, or return nil. For prettier syntax, see the `maybe/1` macro. @@ -67,6 +71,8 @@ defmodule Maybe do maybe(Map.get(map, h), t) end + def maybe(_, _), do: nil + defp extract_keys(ast, keys \\ []) defp extract_keys([], keys), do: keys @@ -88,4 +94,4 @@ defmodule Maybe do keys = keys ++ [key] extract_keys(t, keys) end -end +end \ No newline at end of file From d0b75caf23ef048944739a0ec226833df8f7e53c Mon Sep 17 00:00:00 2001 From: Zachary Berkompas Date: Mon, 5 Feb 2018 09:34:12 -0800 Subject: [PATCH 2/3] Minor update --- lib/maybe.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/maybe.ex b/lib/maybe.ex index 61c8fb5..564cbf7 100644 --- a/lib/maybe.ex +++ b/lib/maybe.ex @@ -67,7 +67,7 @@ defmodule Maybe do def maybe(nil, _keys), do: nil def maybe(val, []), do: val - def maybe(map, [h | t]) do + def maybe(map, [h | t]) when is_map(map) do maybe(Map.get(map, h), t) end From 68ef1c0052232d169138974ffb9c0a61e1475d8e Mon Sep 17 00:00:00 2001 From: Zachary Berkompas Date: Mon, 5 Feb 2018 09:37:25 -0800 Subject: [PATCH 3/3] Format --- lib/maybe.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/maybe.ex b/lib/maybe.ex index 564cbf7..0332aa0 100644 --- a/lib/maybe.ex +++ b/lib/maybe.ex @@ -94,4 +94,4 @@ defmodule Maybe do keys = keys ++ [key] extract_keys(t, keys) end -end \ No newline at end of file +end