Skip to content

Commit

Permalink
Adding more filters
Browse files Browse the repository at this point in the history
  • Loading branch information
ineiti committed Nov 28, 2023
1 parent c2e6087 commit 4c2e476
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
28 changes: 28 additions & 0 deletions mino/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package mino

import (
"math/rand"
"sort"
)

Expand Down Expand Up @@ -68,6 +69,19 @@ func IndexFilter(index int) FilterUpdater {
}
}

// RejectFilter removes the given index
func RejectFilter(index int) FilterUpdater {
return func(filters *Filter) {
arr := filters.Indices
i := sort.IntSlice(arr).Search(index)
// do nothing if the element is not there
if i == len(arr) || arr[i] != index {
return
}
filters.Indices = append(filters.Indices[0:i], filters.Indices[i+1:]...)
}
}

// RangeFilter is a filter to include a range of indices.
// It will add all indices from start..end-1 to the existing
// indices.
Expand Down Expand Up @@ -97,3 +111,17 @@ func ListFilter(indices []int) FilterUpdater {
filters.Indices = indices
}
}

// RandomFilter chooses 'count' random elements.
func RandomFilter(count int) FilterUpdater {
return func(filters *Filter) {
if len(filters.Indices) >= count {
return
}
rand.Shuffle(len(filters.Indices),
func(i, j int) {
filters.Indices[i], filters.Indices[j] = filters.Indices[j], filters.Indices[i]
})
filters.Indices = filters.Indices[:count]
}
}
34 changes: 29 additions & 5 deletions mino/option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,44 @@ func TestFilter_RotateFilter(t *testing.T) {

func TestFilter_IndexFilter(t *testing.T) {
filters := &Filter{Indices: []int{}}

IndexFilter(1)(filters)
require.Equal(t, filters.Indices, []int{1})
require.Equal(t, []int{1}, filters.Indices)

IndexFilter(2)(filters)
require.Equal(t, []int{1, 2}, filters.Indices)

IndexFilter(2)(filters)
require.Equal(t, filters.Indices, []int{1, 2})
require.Equal(t, []int{1, 2}, filters.Indices)

IndexFilter(0)(filters)
require.Equal(t, filters.Indices, []int{0, 1, 2})
require.Equal(t, []int{0, 1, 2}, filters.Indices)

IndexFilter(0)(filters)
IndexFilter(1)(filters)
IndexFilter(2)(filters)
require.Equal(t, filters.Indices, []int{0, 1, 2})
require.Equal(t, []int{0, 1, 2}, filters.Indices)
}

func TestFilter_RejectFilter(t *testing.T) {
filters := &Filter{Indices: []int{1, 2, 3, 4}}

testCases := []struct {
filterVal int
expected []int
}{
{0, []int{1, 2, 3, 4}},
{5, []int{1, 2, 3, 4}},
{2, []int{1, 3, 4}},
{1, []int{3, 4}},
{4, []int{3}},
{4, []int{3}},
{3, []int{}},
}

for _, tc := range testCases {
RejectFilter(tc.filterVal)(filters)
require.Equal(t, tc.expected, filters.Indices)
}
}

func TestFilter_RangeFilter(t *testing.T) {
Expand Down

0 comments on commit 4c2e476

Please sign in to comment.