@@ -138,12 +138,15 @@ defmodule Jsonpatch do
138138
139139 # ===== ===== PRIVATE ===== =====
140140
141+ # Helper for better readability
141142 defguardp are_unequal_maps ( val1 , val2 )
142143 when val1 != val2 and is_map ( val2 ) and is_map ( val1 )
143144
145+ # Helper for better readability
144146 defguardp are_unequal_lists ( val1 , val2 )
145147 when val1 != val2 and is_list ( val2 ) and is_list ( val1 )
146148
149+ # Diff reduce loop
147150 defp do_diff ( destination , source , ancestor_path , acc \\ [ ] , checked_keys \\ [ ] )
148151
149152 defp do_diff ( [ ] , source , ancestor_path , acc , checked_keys ) do
@@ -163,16 +166,9 @@ defmodule Jsonpatch do
163166 defp do_diff ( [ { key , val } | tail ] , source , ancestor_path , acc , checked_keys )
164167 when is_list ( source ) or is_map ( source ) do
165168 current_path = "#{ ancestor_path } /#{ escape ( key ) } "
166- checked_keys = [ escape ( key ) | checked_keys ]
167-
168- from_source =
169- cond do
170- is_map ( source ) -> Map . get ( source , key )
171- is_list ( source ) -> Enum . at ( source , key )
172- end
173169
174170 acc =
175- case from_source do
171+ case get ( source , key ) do
176172 # Key is not present in source
177173 nil ->
178174 [ % Add { path: current_path , value: val } | acc ]
@@ -192,15 +188,25 @@ defmodule Jsonpatch do
192188 end
193189
194190 # Diff next value of same level
195- do_diff ( tail , source , ancestor_path , acc , checked_keys )
191+ do_diff ( tail , source , ancestor_path , acc , [ escape ( key ) | checked_keys ] )
196192 end
197193
198194 # Transforms a map into a tuple list and a list also into a tuple list with indizes
199- defp flat ( val ) do
200- cond do
201- is_list ( val ) -> Stream . with_index ( val ) |> Enum . map ( fn { v , k } -> { k , v } end )
202- is_map ( val ) -> Map . to_list ( val )
203- end
195+ defp flat ( val ) when is_list ( val ) do
196+ Stream . with_index ( val ) |> Enum . map ( fn { v , k } -> { k , v } end )
197+ end
198+
199+ defp flat ( val ) when is_map ( val ) do
200+ Map . to_list ( val )
201+ end
202+
203+ # Unified access to lists or maps
204+ defp get ( source , key ) when is_list ( source ) do
205+ Enum . at ( source , key )
206+ end
207+
208+ defp get ( source , key ) do
209+ Map . get ( source , key )
204210 end
205211
206212 # Escape `/` to `~1 and `~` to `~`.
0 commit comments