Skip to content

Commit 543ecda

Browse files
author
Ben Baumgold
committed
new method implementations for Stack
1 parent 1c6c2ad commit 543ecda

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/stack.jl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,16 @@ Get the top item from the stack. Sometimes called peek.
4343
Base.first(s::Stack) = last(s.store)
4444
Base.last(s::Stack) = first(s.store)
4545

46-
function Base.push!(s::Stack, x)
47-
push!(s.store, x)
48-
return s
49-
end
46+
Base.push!(s::Stack, x) = (push!(s.store, x); s)
47+
Base.pushfirst!(s::Stack, x) = (pushfirst!(s.store, x); s)
5048

5149
Base.pop!(s::Stack) = pop!(s.store)
50+
Base.popfirst!(s::Stack) = popfirst!(s.store)
5251

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

54+
Base.collect(s::Stack) = collect(s.store)
55+
5556
Base.iterate(st::Stack, s...) = iterate(Iterators.reverse(st.store), s...)
5657

5758
Iterators.reverse(s::Stack{T}) where {T} = DequeIterator{T}(s.store)

test/test_stack.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,28 @@
3838
@test isempty(s) == (i == n)
3939
@test length(s) == n - i
4040
end
41+
42+
for i = 1 : n
43+
pushfirst!(s, i)
44+
@test first(s) == 1
45+
@test last(s) == i
46+
@test !isempty(s)
47+
@test length(s) == i
48+
end
49+
50+
@test collect(s) == collect(n:-1:1)
51+
52+
for i = 1 : n
53+
x = popfirst!(s)
54+
@test x == n - i + 1
55+
if i < n
56+
@test first(s) == 1
57+
else
58+
@test_throws ArgumentError first(s)
59+
end
60+
@test isempty(s) == (i == n)
61+
@test length(s) == n - i
62+
end
4163
end
4264

4365
@testset "==" begin

0 commit comments

Comments
 (0)