Skip to content

Commit 4e3d9e5

Browse files
aplavinjw3126
andauthored
Add delete with Elements optic (#206)
* Fix delete with Elements optic - fixes #176 - Add delete methods for Elements optic that create empty collections - Add tests for Elements delete functionality including nested cases Co-authored-by: Jan Weidner <jw3126@gmail.com>
1 parent 2bbc797 commit 4e3d9e5

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/optics.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,10 @@ modify(f, obj, ::Elements) = map(f, obj)
249249
modify(f, obj::Set, ::Elements) = Set(f(p) for p in obj)
250250
modify(f, obj::Dict, ::Elements) = Dict(f(p)::Pair for p in obj)
251251

252+
# delete all elements, creating an empty collection of the same type
253+
delete(obj::Union{Tuple, NamedTuple, AbstractVector, AbstractDict, AbstractSet}, ::Elements) = empty(obj)
254+
delete(obj::AbstractString, ::Elements) = ""
255+
252256
"""
253257
If(modify_condition)
254258

test/test_insert_delete.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,16 @@ end
124124
@test delete( (a=1, b=(2, 3, 4)), @optic(first(_.b)) ) == (a=1, b=(3, 4))
125125
@test delete( "path/to/file", @optic(basename(_)) ) == "path/to"
126126
@test delete( "path/to/file", @optic(dirname(_)) ) == "file"
127+
128+
# delete with Elements creates empty collections
129+
@test delete((1, 2, 3), Elements()) === ()
130+
@test delete([1, 2, 3], Elements()) == Int[]
131+
@test delete(Set([1, 2, 3]), Elements()) == Set{Int}()
132+
@test delete(Dict(1 => :a, 2 => :b), Elements()) == Dict{Int, Symbol}()
133+
@test delete((a=1, b=2, c=3), Elements()) === NamedTuple()
134+
# nested case: delete all elements from nested collections
135+
nested_dict = Dict("a" => (1, 2, 3))
136+
@test delete(nested_dict, @optic _["a"][]) == Dict("a" => ())
127137
end
128138

129139
@testset "macro" begin

0 commit comments

Comments
 (0)