瀏覽代碼

add fx.Count

kevin 4 年之前
父節點
當前提交
637a94a189
共有 2 個文件被更改,包括 38 次插入0 次删除
  1. 8 0
      core/fx/fn.go
  2. 30 0
      core/fx/fn_test.go

+ 8 - 0
core/fx/fn.go

@@ -84,6 +84,14 @@ func (p Stream) Buffer(n int) Stream {
 	return Range(source)
 	return Range(source)
 }
 }
 
 
+// Count counts the number of elements in the result.
+func (p Stream) Count() (count int) {
+	for range p.source {
+		count++
+	}
+	return
+}
+
 // Distinct removes the duplicated items base on the given KeyFunc.
 // Distinct removes the duplicated items base on the given KeyFunc.
 func (p Stream) Distinct(fn KeyFunc) Stream {
 func (p Stream) Distinct(fn KeyFunc) Stream {
 	source := make(chan interface{})
 	source := make(chan interface{})

+ 30 - 0
core/fx/fn_test.go

@@ -49,6 +49,36 @@ func TestBufferNegative(t *testing.T) {
 	assert.Equal(t, 10, result)
 	assert.Equal(t, 10, result)
 }
 }
 
 
+func TestCount(t *testing.T) {
+	tests := []struct {
+		name     string
+		elements []interface{}
+	}{
+		{
+			name: "no elements with nil",
+		},
+		{
+			name:     "no elements",
+			elements: []interface{}{},
+		},
+		{
+			name:     "1 element",
+			elements: []interface{}{1},
+		},
+		{
+			name:     "multiple elements",
+			elements: []interface{}{1, 2, 3},
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			val := Just(test.elements...).Count()
+			assert.Equal(t, len(test.elements), val)
+		})
+	}
+}
+
 func TestDone(t *testing.T) {
 func TestDone(t *testing.T) {
 	var count int32
 	var count int32
 	Just(1, 2, 3).Walk(func(item interface{}, pipe chan<- interface{}) {
 	Just(1, 2, 3).Walk(func(item interface{}, pipe chan<- interface{}) {