Skip to content

Commit 743ee8c

Browse files
authored
filter(f, ::NamedTuple) (#839)
1 parent 001cc41 commit 743ee8c

File tree

4 files changed

+21
-1
lines changed

4 files changed

+21
-1
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "Compat"
22
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
3-
version = "4.16.0"
3+
version = "4.17.0"
44

55
[deps]
66
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ changes in `julia`.
7272

7373
## Supported features
7474

75+
* `filter` can now act on a `NamedTuple` [#50795]. (since Compat 4.17.0)
76+
7577
* `insertdims(D; dims)` is the opposite of `dropdims` ([#45793]) (since Compat 4.16.0)
7678

7779
* `Compat.Fix{N}` which fixes an argument at the `N`th position ([#54653]) (since Compat 4.16.0)
@@ -197,4 +199,5 @@ Note that you should specify the correct minimum version for `Compat` in the
197199
[#47679]: https://github.com/JuliaLang/julia/pull/47679
198200
[#48038]: https://github.com/JuliaLang/julia/issues/48038
199201
[#50105]: https://github.com/JuliaLang/julia/issues/50105
202+
[#50795]: https://github.com/JuliaLang/julia/issues/50795
200203
[#54653]: https://github.com/JuliaLang/julia/issues/54653

src/Compat.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,14 @@ if VERSION < v"1.11.0-DEV.1562"
797797
end
798798
end
799799

800+
# https://github.com/JuliaLang/julia/pull/50795
801+
if VERSION < v"1.11.0-DEV.1457"
802+
Base.filter(f, xs::NamedTuple) = _getindex(xs, filter(k -> f(xs[k]), keys(xs)))
803+
# `getindex(::NamedTuple, ::Tuple{Vararg{Symbol}})` is not defined in Julia 1.6.
804+
# Introduced in https://github.com/JuliaLang/julia/pull/38878.
805+
@inline _getindex(t::NamedTuple, idxs::Tuple{Vararg{Symbol}}) = NamedTuple{idxs}(t)
806+
end
807+
800808
# https://github.com/JuliaLang/julia/pull/45052
801809
if VERSION < v"1.9.0-DEV.461"
802810
Base.VersionNumber(v::VersionNumber) = v

test/runtests.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,3 +1071,12 @@ end
10711071
end
10721072
end
10731073
end
1074+
1075+
# https://github.com/JuliaLang/julia/pull/50795
1076+
@testset "filter on NamedTuple" begin
1077+
@test filter(isodd, (a=1,b=2,c=3)) === (a=1, c=3)
1078+
@test filter(i -> true, (;)) === (;)
1079+
longnt = NamedTuple{ntuple(i -> Symbol(:a, i), 20)}(ntuple(identity, 20))
1080+
@test filter(iseven, longnt) === NamedTuple{ntuple(i -> Symbol(:a, 2i), 10)}(ntuple(i -> 2i, 10))
1081+
@test filter(x -> x<2, (longnt..., z=1.5)) === (a1=1, z=1.5)
1082+
end

0 commit comments

Comments
 (0)