From 952300c15c5494e52f49c885d4d1b3de0d2e162e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bogumi=C5=82=20Kami=C5=84ski?= Date: Wed, 1 Jun 2022 18:55:48 +0200 Subject: [PATCH] [3.x] add popat! (#774) --- Project.toml | 2 +- README.md | 4 ++++ src/Compat.jl | 21 +++++++++++++++++++++ test/runtests.jl | 15 +++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 115785030..b450a44ca 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "Compat" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" -version = "3.44.0" +version = "3.45.0" [deps] Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" diff --git a/README.md b/README.md index dcebc9be4..111c5892c 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,9 @@ changes in `julia`. ## Supported features +* `popat!` removes the item at the given `i` and returns it ([#36070]). (since + Compat 3.45.0) + * `keepat!` removes the items at all the indices which are not given and returns the modified source ([#36229], [#42351]). (since Compat 3.44.0, 4.1.0) @@ -298,6 +301,7 @@ Note that you should specify the correct minimum version for `Compat` in the [#29790]: https://github.com/JuliaLang/julia/pull/29790 [#38449]: https://github.com/JuliaLang/julia/pull/38449 [#36018]: https://github.com/JuliaLang/julia/pull/36018 +[#36070]: https://github.com/JuliaLang/julia/pull/36070 [#36199]: https://github.com/JuliaLang/julia/pull/36199 [#37454]: https://github.com/JuliaLang/julia/pull/37454 [#40729]: https://github.com/JuliaLang/julia/pull/40729 diff --git a/src/Compat.jl b/src/Compat.jl index c9e915a72..090739a13 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -1365,6 +1365,27 @@ end end end +# This function is available as of Julia 1.5. +@static if !isdefined(Base, :popat!) + export popat! + + function popat!(a::Vector, i::Integer) + x = a[i] + Base._deleteat!(a, i, 1) + x + end + + function popat!(a::Vector, i::Integer, default) + if 1 <= i <= length(a) + x = @inbounds a[i] + Base._deleteat!(a, i, 1) + x + else + default + end + end +end + include("iterators.jl") include("deprecated.jl") diff --git a/test/runtests.jl b/test/runtests.jl index e164cda17..f6f358d83 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1451,3 +1451,18 @@ end keepat!(ea, Bool[]) @test isempty(ea) end + +@testset "popat!(::Vector, i, [default])" begin + a = [1, 2, 3, 4] + @test_throws BoundsError popat!(a, 0) + @test popat!(a, 0, "default") == "default" + @test a == 1:4 + @test_throws BoundsError popat!(a, 5) + @test popat!(a, 1) == 1 + @test a == [2, 3, 4] + @test popat!(a, 2) == 3 + @test a == [2, 4] + @test popat!(a, 1, "default") == 2 + badpop() = @inbounds popat!([1], 2) + @test_throws BoundsError badpop() +end