Skip to content

Commit c77d293

Browse files
committed
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
1 parent 18e9ddb commit c77d293

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
@@ -247,6 +247,10 @@ modify(f, obj, ::Elements) = map(f, obj)
247247
modify(f, obj::Set, ::Elements) = Set(f(p) for p in obj)
248248
modify(f, obj::Dict, ::Elements) = Dict(f(p)::Pair for p in obj)
249249

250+
# delete all elements, creating an empty collection of the same type
251+
delete(obj::Union{Tuple, NamedTuple, AbstractVector, AbstractDict, Set}, ::Elements) = empty(obj)
252+
delete(obj::AbstractString, ::Elements) = ""
253+
250254
"""
251255
If(modify_condition)
252256

test/test_insert_delete.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ end
120120
@test delete( (a=1, b=(2, 3, 4)), @optic(first(_.b)) ) == (a=1, b=(3, 4))
121121
@test delete( "path/to/file", @optic(basename(_)) ) == "path/to"
122122
@test delete( "path/to/file", @optic(dirname(_)) ) == "file"
123+
124+
# delete with Elements creates empty collections
125+
@test delete((1, 2, 3), Elements()) === ()
126+
@test delete([1, 2, 3], Elements()) == Int[]
127+
@test delete(Set([1, 2, 3]), Elements()) == Set{Int}()
128+
@test delete(Dict(1 => :a, 2 => :b), Elements()) == Dict{Int, Symbol}()
129+
@test delete((a=1, b=2, c=3), Elements()) === NamedTuple()
130+
# nested case: delete all elements from nested collections
131+
nested_dict = Dict("a" => (1, 2, 3))
132+
@test delete(nested_dict, @optic _["a"][]) == Dict("a" => ())
123133
end
124134

125135
@testset "macro" begin

0 commit comments

Comments
 (0)