Skip to content
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