Skip to content

Commit

Permalink
new method implementations for Stack
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Baumgold committed Jun 10, 2022
1 parent 1c6c2ad commit e9b21b4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "DataStructures"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.19.0-DEV"
version = "0.18.0"

[deps]
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"
Expand Down
9 changes: 5 additions & 4 deletions src/stack.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,16 @@ Get the top item from the stack. Sometimes called peek.
Base.first(s::Stack) = last(s.store)
Base.last(s::Stack) = first(s.store)

function Base.push!(s::Stack, x)
push!(s.store, x)
return s
end
Base.push!(s::Stack, x) = (push!(s.store, x); s)
Base.pushfirst!(s::Stack, x) = (pushfirst!(s.store, x); s)

Base.pop!(s::Stack) = pop!(s.store)
Base.popfirst!(s::Stack) = popfirst!(s.store)

Base.empty!(s::Stack) = (empty!(s.store); s)

Base.collect(s::Stack) = collect(s.store)

Base.iterate(st::Stack, s...) = iterate(Iterators.reverse(st.store), s...)

Iterators.reverse(s::Stack{T}) where {T} = DequeIterator{T}(s.store)
Expand Down
22 changes: 22 additions & 0 deletions test/test_stack.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,28 @@
@test isempty(s) == (i == n)
@test length(s) == n - i
end

for i = 1 : n
pushfirst!(s, i)
@test first(s) == 1
@test last(s) == i
@test !isempty(s)
@test length(s) == i
end

@test collect(s) == collect(n:-1:1)

for i = 1 : n
x = popfirst!(s)
@test x == n - i + 1
if i < n
@test first(s) == 1
else
@test_throws ArgumentError first(s)
end
@test isempty(s) == (i == n)
@test length(s) == n - i
end
end

@testset "==" begin
Expand Down

0 comments on commit e9b21b4

Please sign in to comment.