-
Notifications
You must be signed in to change notification settings - Fork 206
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: extract slice and integer methods to helper file (utils.go)
- Loading branch information
1 parent
f184359
commit 959f516
Showing
2 changed files
with
71 additions
and
59 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package table | ||
|
||
import "golang.org/x/exp/slices" | ||
|
||
// btoi converts a boolean to an integer, 1 if true, 0 if false. | ||
func btoi(b bool) int { | ||
if b { | ||
return 1 | ||
} | ||
return 0 | ||
} | ||
|
||
// max returns the greater of two integers. | ||
func max(a, b int) int { | ||
if a > b { | ||
return a | ||
} | ||
return b | ||
} | ||
|
||
// min returns the greater of two integers. | ||
func min(a, b int) int { | ||
if a < b { | ||
return a | ||
} | ||
return b | ||
} | ||
|
||
// sum returns the sum of all integers in a slice. | ||
func sum(n []int) int { | ||
var sum int | ||
for _, i := range n { | ||
sum += i | ||
} | ||
return sum | ||
} | ||
|
||
// median returns the median of a slice of integers. | ||
func median(n []int) int { | ||
slices.Sort(n) | ||
|
||
if len(n) <= 0 { | ||
return 0 | ||
} | ||
if len(n)%2 == 0 { | ||
return (n[len(n)/2-1] + n[len(n)/2]) / 2 | ||
} | ||
return n[len(n)/2] | ||
} | ||
|
||
// largest returns the largest element and it's index from a slice of integers. | ||
func largest(n []int) (int, int) { // nolint: unparam | ||
var largest, index int | ||
for i, e := range n { | ||
if n[i] > n[index] { | ||
largest = e | ||
index = i | ||
} | ||
} | ||
return index, largest | ||
} |