From af23793a57f2436814052d120310d6edba3415d5 Mon Sep 17 00:00:00 2001 From: TheBoringDude Date: Sun, 30 May 2021 22:11:24 +0800 Subject: [PATCH] collections `filter` functions - FilterString() - returns all string elems - FilterInt() - returns all int elems - FilterBool() - returns all bool elems - FilterFloat() - returns all float elements --- collections-query.go | 52 +++++++++++++++++++++++++++++++++++++++ collections-query_test.go | 33 ++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/collections-query.go b/collections-query.go index 696aa5a..a766670 100644 --- a/collections-query.go +++ b/collections-query.go @@ -81,3 +81,55 @@ func (c *MiniCollections) MatchStringAll(v string) ([]string, error) { return values, nil } + +// FilterString returns all string elements. +func (c *MiniCollections) FilterString() []string { + values := []string{} + + for _, i := range c.store { + if v, ok := i.(string); ok { + values = append(values, v) + } + } + + return values +} + +// FilterInt returns all int elements. +func (c *MiniCollections) FilterInt() []int { + values := []int{} + + for _, i := range c.store { + if v, ok := i.(int); ok { + values = append(values, v) + } + } + + return values +} + +// FilterBool returns all bool elements. +func (c *MiniCollections) FilterBool() []bool { + values := []bool{} + + for _, i := range c.store { + if v, ok := i.(bool); ok { + values = append(values, v) + } + } + + return values +} + +// FilterFloat returns all float elements (uses float64). Some integers (int) might be included. +func (c *MiniCollections) FilterFloat() []float64 { + values := []float64{} + + for _, i := range c.store { + if v, ok := i.(float64); ok { + values = append(values, v) + } + } + + return values +} diff --git a/collections-query_test.go b/collections-query_test.go index 0b6ff0c..17784f4 100644 --- a/collections-query_test.go +++ b/collections-query_test.go @@ -1,6 +1,9 @@ package minidb -import "testing" +import ( + "reflect" + "testing" +) func TestPush_Collections(t *testing.T) { filename := "pushcols.json" @@ -99,3 +102,31 @@ func TestMatchStringAll_Collections(t *testing.T) { t.Fatal("wrong return value from match string all") } } + +func TestFilter(t *testing.T) { + filename := "filter.json" + defer cleanFileAfter(filename, t) + + db := NewMiniCollections(filename) + + db.Push("hellox") + db.Push("sample") + db.Push(1) + db.Push(100) + db.Push(false) + + frString := []string{"hellox", "sample"} + if !reflect.DeepEqual(db.FilterString(), frString) { + t.Fatal("wrong filter string output") + } + + frInt := []int{1, 100} + if !reflect.DeepEqual(db.FilterInt(), frInt) { + t.Fatal("wrong filter int output") + } + + frBool := []bool{false} + if !reflect.DeepEqual(db.FilterBool(), frBool) { + t.Fatal("wrong filter bool output") + } +}