Skip to content

Commit

Permalink
day 144: bounds check with a panic
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 17, 2019
1 parent aa56c17 commit 0ceecd5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
3 changes: 3 additions & 0 deletions day144/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ package day144
// If no number if found, then -1 is returned.
// Runs in O(N) time.
func ClosestLargerNumberIndexBrute(nums []int, targetIndex int) int {
if targetIndex < 0 || targetIndex >= len(nums) {
panic("index out of bounds")
}
val := nums[targetIndex]
left, right := targetIndex-1, targetIndex+1
for left >= 0 || right < len(nums) {
Expand Down
10 changes: 10 additions & 0 deletions day144/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ func TestClosestLargerNumberIndexBrute(t *testing.T) {
}
}

func TestClosestLargerNumberIndexBruteBoundsCheck(t *testing.T) {
t.Parallel()
defer func() {
if err := recover(); err == nil {
t.Errorf("It should panic with an index out of bounds")
}
}()
ClosestLargerNumberIndexBrute([]int{1, 2}, 3)
}

func BenchmarkClosestLargerNumberIndexBrute(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Expand Down

0 comments on commit 0ceecd5

Please sign in to comment.