Skip to content

Commit

Permalink
collections filter functions
Browse files Browse the repository at this point in the history
- FilterString() - returns all string elems
- FilterInt() - returns all int elems
- FilterBool() - returns all bool elems
- FilterFloat() - returns all float elements
  • Loading branch information
tbdsux committed May 30, 2021
1 parent b854476 commit af23793
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
52 changes: 52 additions & 0 deletions collections-query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
33 changes: 32 additions & 1 deletion collections-query_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package minidb

import "testing"
import (
"reflect"
"testing"
)

func TestPush_Collections(t *testing.T) {
filename := "pushcols.json"
Expand Down Expand Up @@ -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")
}
}

0 comments on commit af23793

Please sign in to comment.