Implement pfs.Filter()

TODO
filtering
This commit is contained in:
pocke 2015-01-08 10:04:30 +09:00
parent 7b75facf1c
commit 28cebd4985
2 changed files with 60 additions and 4 deletions

27
pfs.go
View File

@ -60,6 +60,12 @@ func (p *PFS) Sub(f interface{}) error {
// TODO: check fn arguments
}
p.fmu.RLock()
if len(p.filters) != 0 {
// TODO: check fn arguments
}
p.fmu.RUnlock()
p.listeners = append(p.listeners, fn)
return nil
}
@ -69,6 +75,27 @@ func (p *PFS) Off() {
}
func (p *PFS) Filter(f interface{}) error {
p.fmu.Lock()
defer p.fmu.Unlock()
// TODO: DRY
fn := reflect.ValueOf(f)
if reflect.Func != fn.Kind() {
return fmt.Errorf("Argument should be a function")
}
p.lmu.RLock()
if len(p.listeners) != 0 {
// TODO: check fn arguments
}
p.lmu.RUnlock()
if len(p.filters) != 0 {
// TODO: check fn arguments
}
p.filters = append(p.filters, fn)
return nil
}

View File

@ -12,17 +12,17 @@ func TestPFSNew(t *testing.T) {
}
func TestPubSub(t *testing.T) {
pfs := pfs.New()
p := pfs.New()
i := 1
err := pfs.Sub(func(j int) {
err := p.Sub(func(j int) {
i += j
})
if err != nil {
t.Error(err)
t.Fatal(err)
}
pfs.Pub(2)
p.Pub(2)
if i != 3 {
t.Errorf("Expected i == 3, Got i == %d", i)
@ -36,3 +36,32 @@ func TestSubWhenNotFunction(t *testing.T) {
t.Error("should return error When recieve not function. But got nil.")
}
}
func TestFilter(t *testing.T) {
p := pfs.New()
i := 1
err := p.Sub(func(j int) {
i += j
})
if err != nil {
t.Fatal(err)
}
err = p.Filter(func(j int) bool {
return j == 3
})
if err != nil {
t.Fatal(err)
}
p.Pub(2)
if i != 3 {
t.Errorf("Expected i == 3, Got i == %d", i)
}
p.Pub(3)
if i != 3 {
t.Errorf("Expected i == 3, Got i == %d", i)
}
}