Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new method implementations for Stack #816

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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