Skip to content

Commit

Permalink
[#1] Error for get/2, default value for get/3.
Browse files Browse the repository at this point in the history
  • Loading branch information
jfacorro committed Aug 12, 2014
1 parent b249dd5 commit aa3a64d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 18 deletions.
33 changes: 22 additions & 11 deletions src/ktn_maps.erl
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,35 @@
get/3
]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Public API
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

-spec get(term(), map()) -> term().
get(Keys, Map) ->
get(Keys, Map, undefined).
get(Keys, Map, undefined, error).

-spec get(term(), map(), term()) -> term().
get([Key], Map, Default) ->
get(Key, Map, Default);
get([Key | Rest], Map, Default) ->
case get(Key, Map, Default) of
get(Keys, Map, Default) ->
get(Keys, Map, Default, default).

%% @private
-spec get(term(), map(), term(), error | default) -> term().
get([Key], Map, Default, Type) ->
get(Key, Map, Default, Type);
get([Key | Rest], Map, Default, Type) ->
case get(Key, Map, Default, Type) of
NewMap when is_map(NewMap) ->
get(Rest, NewMap, Default);
get(Rest, NewMap, Default, Type);
_ ->
Default
end;
get(Key, Map, Default) ->
case maps:is_key(Key, Map) of
true ->
get(Key, Map, Default, Type) ->
case {Type, maps:is_key(Key, Map)} of
{_, true} ->
maps:get(Key, Map);
false ->
Default
{default, false} ->
Default;
{error, false} ->
error(bad_path)
end.
32 changes: 25 additions & 7 deletions test/ktn_maps_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,35 @@ find_shallow_values(Config) ->
-spec dont_find_nested_values(config()) -> ok.
dont_find_nested_values(Config) ->
Map = proplists:get_value(map, Config),
undefined = ktn_maps:get([address, country, city], Map),
undefined = ktn_maps:get([social, facebook], Map).

ok = try
ktn_maps:get([address, country, city], Map)
catch
error:bad_path -> ok
end,
ok = try
ktn_maps:get([social, facebook], Map)
catch
error:bad_path -> ok
end.

-spec dont_find_shallow_values(config()) -> ok.
dont_find_shallow_values(Config) ->
Map = proplists:get_value(map, Config),
undefined = ktn_maps:get(username, Map),
undefined = ktn_maps:get(email, Map),
undefined = ktn_maps:get([email], Map).

ok = try
ktn_maps:get(username, Map)
catch
error:bad_path -> ok
end,
ok = try
ktn_maps:get(email, Map)
catch
error:bad_path -> ok
end,
ok = try
ktn_maps:get([email], Map)
catch
error:bad_path -> ok
end.

-spec provide_default(config()) -> ok.
provide_default(Config) ->
Expand Down

0 comments on commit aa3a64d

Please sign in to comment.