From 10cfda1f8634f2cea4b983e49b388a35bcd2a11a Mon Sep 17 00:00:00 2001 From: lowzj Date: Sun, 26 Apr 2020 09:29:06 +0800 Subject: [PATCH] fix: GCDSlice returns 1 when slice is empty Signed-off-by: lowzj --- dfget/config/supernode_value.go | 2 +- pkg/algorithm/algorithm.go | 5 +++++ pkg/algorithm/algorithm_test.go | 2 ++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/dfget/config/supernode_value.go b/dfget/config/supernode_value.go index 96c6b8be2..525b2e85b 100644 --- a/dfget/config/supernode_value.go +++ b/dfget/config/supernode_value.go @@ -152,7 +152,7 @@ func ParseNodesSlice(value []string) ([]*NodeWeight, error) { for _, v := range nodeWeightSlice { result = append(result, &NodeWeight{ Node: v.Node, - Weight: (v.Weight / gcdNumber), + Weight: v.Weight / gcdNumber, }) } diff --git a/pkg/algorithm/algorithm.go b/pkg/algorithm/algorithm.go index 942f5a93d..560532d7c 100644 --- a/pkg/algorithm/algorithm.go +++ b/pkg/algorithm/algorithm.go @@ -17,8 +17,13 @@ package algorithm // GCDSlice returns the greatest common divisor of a slice. +// It returns 1 when s is empty because that any number divided by 1 is still +// itself. func GCDSlice(s []int) int { length := len(s) + if length == 0 { + return 1 + } if length == 1 { return s[0] } diff --git a/pkg/algorithm/algorithm_test.go b/pkg/algorithm/algorithm_test.go index 2eb808430..f1e51012c 100644 --- a/pkg/algorithm/algorithm_test.go +++ b/pkg/algorithm/algorithm_test.go @@ -53,6 +53,8 @@ func (suit *AlgorithmSuite) TestGCDSlice() { slice []int result int }{ + {nil, 1}, + {[]int{2}, 2}, {[]int{2, 2, 4}, 2}, {[]int{5, 10, 25}, 5}, {[]int{1, 3, 5}, 1},