From a46118ecb36158675f6fcf674e83b818e2215b98 Mon Sep 17 00:00:00 2001 From: alisdair sullivan Date: Fri, 18 Apr 2014 23:43:40 +0000 Subject: [PATCH] refactor out copy/pasted encode methods --- src/jsx_encoder.erl | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/jsx_encoder.erl b/src/jsx_encoder.erl index 0eaf2f2..349da5f 100644 --- a/src/jsx_encoder.erl +++ b/src/jsx_encoder.erl @@ -39,19 +39,32 @@ encode(Term) -> encode(Term, ?MODULE). -spec encode(Term::any(), EntryPoint::module()) -> any(). -encode([], _EntryPoint) -> [start_array, end_array]; -encode([{}], _EntryPoint) -> [start_object, end_object]; +-ifndef(release_supports_maps). +encode(Term, EntryPoint) -> encode_(Term, EntryPoint). +-endif. -encode([{_, _}|_] = Term, EntryPoint) -> +-ifdef(release_supports_maps). +encode(Map, _EntryPoint) when is_map(Map), map_size(Map) < 1 -> [start_object, end_object]; +encode(Term, EntryPoint) when is_map(Term) -> + lists:flatten( + [start_object] ++ [ EntryPoint:encode(T, EntryPoint) || T <- unpack(Term) ] ++ [end_object] + ); +encode(Term, EntryPoint) -> encode_(Term, EntryPoint). +-endif. + +encode_([], _EntryPoint) -> [start_array, end_array]; +encode_([{}], _EntryPoint) -> [start_object, end_object]; + +encode_([{_, _}|_] = Term, EntryPoint) -> lists:flatten( [start_object] ++ [ EntryPoint:encode(T, EntryPoint) || T <- unzip(Term) ] ++ [end_object] ); -encode(Term, EntryPoint) when is_list(Term) -> +encode_(Term, EntryPoint) when is_list(Term) -> lists:flatten( [start_array] ++ [ EntryPoint:encode(T, EntryPoint) || T <- Term ] ++ [end_array] ); -encode(Else, _EntryPoint) -> [Else]. +encode_(Else, _EntryPoint) -> [Else]. unzip(List) -> unzip(List, []). @@ -59,6 +72,15 @@ unzip(List) -> unzip(List, []). unzip([], Acc) -> lists:reverse(Acc); unzip([{K, V}|Rest], Acc) when is_binary(K); is_atom(K); is_integer(K) -> unzip(Rest, [V, K] ++ Acc). +-ifdef(release_supports_maps). +unpack(Map) -> unpack(maps:keys(Map), Map, []). + +unpack([], _, Acc) -> lists:reverse(Acc); +unpack([K|Rest], Map, Acc) when is_binary(K); is_atom(K); is_integer(K) -> + unpack(Rest, Map, [maps:get(K, Map), K] ++ Acc). +-endif. + + -ifdef(TEST). -include_lib("eunit/include/eunit.hrl").