Skip to content

Commit

Permalink
Added Stack.Peek.
Browse files Browse the repository at this point in the history
  • Loading branch information
pat42smith committed Oct 25, 2022
1 parent ac8d005 commit 31a9d30
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
7 changes: 7 additions & 0 deletions stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,10 @@ func (s Stack[T]) Empty() bool {
func (s *Stack[T]) PushMany(ts ...T) {
s.items = append(s.items, ts...)
}

// Peek returns the same value as Pop, but does not remove it from the Stack.
//
// Peek panics when called on an empty Stack.
func (s *Stack[T]) Peek() T {
return s.items[len(s.items)-1]
}
3 changes: 3 additions & 0 deletions stack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,21 @@ func TestThrees(t *testing.T) {
gotest.Expect(t, n/3+2, s.Len())
gotest.Require(t, !s.Empty())

gotest.Expect(t, n+1, s.Peek())
gotest.Expect(t, n+1, s.Pop())
gotest.Expect(t, n/3+1, s.Len())
gotest.Require(t, !s.Empty())
}

for n := 27; n >= 0; n -= 3 {
gotest.Expect(t, n, s.Peek())
gotest.Expect(t, n, s.Pop())
}

gotest.Expect(t, 0, s.Len())
gotest.Require(t, s.Empty())
gotest.MustPanic(t, func() { s.Pop() })
gotest.MustPanic(t, func() { s.Peek() })
}

func TestPushMany(t *testing.T) {
Expand Down

0 comments on commit 31a9d30

Please sign in to comment.