diff options
author | Jesse Duffield <jessedduffield@gmail.com> | 2018-12-05 19:33:46 +1100 |
---|---|---|
committer | Jesse Duffield <jessedduffield@gmail.com> | 2018-12-05 19:33:46 +1100 |
commit | c0f9795910dd840fb83e6992f7f59c77ec4c13fc (patch) | |
tree | 05fe245b822008f458025a5dd75cae384bfda845 /pkg/utils | |
parent | 658e5a9faf8409c62f11f3ad6d636d0255e450f4 (diff) |
staging lines and hunks
Diffstat (limited to 'pkg/utils')
-rw-r--r-- | pkg/utils/utils.go | 21 | ||||
-rw-r--r-- | pkg/utils/utils_test.go | 92 |
2 files changed, 113 insertions, 0 deletions
diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 8e481b3a4..e2a5337e3 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -214,3 +214,24 @@ func IncludesString(list []string, a string) bool { } return false } + +// NextIndex returns the index of the element that comes after the given number +func NextIndex(numbers []int, currentNumber int) int { + for index, number := range numbers { + if number > currentNumber { + return index + } + } + return 0 +} + +// PrevIndex returns the index that comes before the given number, cycling if we reach the end +func PrevIndex(numbers []int, currentNumber int) int { + end := len(numbers) - 1 + for i := end; i >= 0; i -= 1 { + if numbers[i] < currentNumber { + return i + } + } + return end +} diff --git a/pkg/utils/utils_test.go b/pkg/utils/utils_test.go index 41774051b..f03bc087a 100644 --- a/pkg/utils/utils_test.go +++ b/pkg/utils/utils_test.go @@ -425,3 +425,95 @@ func TestIncludesString(t *testing.T) { assert.EqualValues(t, s.expected, IncludesString(s.list, s.element)) } } + +func TestNextIndex(t *testing.T) { + type scenario struct { + testName string + list []int + element int + expected int + } + + scenarios := []scenario{ + { + // I'm not really fussed about how it behaves here + "no elements", + []int{}, + 1, + 0, + }, + { + "one element", + []int{1}, + 1, + 0, + }, + { + "two elements", + []int{1, 2}, + 1, + 1, + }, + { + "two elements, giving second one", + []int{1, 2}, + 2, + 0, + }, + { + "three elements, giving second one", + []int{1, 2, 3}, + 2, + 2, + }, + } + + for _, s := range scenarios { + t.Run(s.testName, func(t *testing.T) { + assert.EqualValues(t, s.expected, NextIndex(s.list, s.element)) + }) + } +} + +func TestPrevIndex(t *testing.T) { + type scenario struct { + testName string + list []int + element int + expected int + } + + scenarios := []scenario{ + { + // I'm not really fussed about how it behaves here + "no elements", + []int{}, + 1, + -1, + }, + { + "one element", + []int{1}, + 1, + 0, + }, + { + "two elements", + []int{1, 2}, + 1, + 1, + }, + { + "three elements, giving second one", + []int{1, 2, 3}, + 2, + 0, + }, + } + + for _, s := range scenarios { + t.Run(s.testName, func(t *testing.T) { + assert.EqualValues(t, s.expected, PrevIndex(s.list, s.element)) + }) + } +} |