Last active
January 2, 2016 08:09
-
-
Save whyrusleeping/8274404 to your computer and use it in GitHub Desktop.
quick go linq hack, proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type T interface{} | |
type Collection []interface{} | |
func From(i T) Collection { | |
var out Collection | |
arr := i.([]interface{}) | |
for _,v := range arr { | |
out = append(out, v) | |
} | |
return out | |
} | |
func (c Collection) Where(chk func (v T) bool) Collection { | |
var out Collection | |
out = make(Collection, 0, len(c)) | |
for _,v := range c { | |
if chk(v) { | |
out = append(out, v) | |
} | |
} | |
return out | |
} | |
func (c Collection) Do(act func (T)) { | |
for _,v := range c { | |
act(v) | |
} | |
} | |
func (c Collection) pDo(act func (T)) { | |
done := make(chan bool) | |
for _,v := range c { | |
go func(i T) { | |
act(i) | |
done<-true | |
}(v) | |
} | |
for i := 0; i < len(c); i++ { | |
<-done | |
} | |
} | |
type pResp struct { | |
ok bool | |
v T | |
} | |
//Paralellized filtering of collections | |
func (c Collection) pWhere(chk func (v T) bool) Collection { | |
var out Collection | |
out = make(Collection, 0, len(c)) | |
coll := make(chan *pResp) | |
async := func (n T, c chan *pResp) { | |
v := n | |
if chk(v) { | |
c <- &pResp{true,v} | |
} else { | |
c <- &pResp{false,nil} | |
} | |
} | |
for _,v := range c { | |
go async(v, coll) | |
} | |
for i := 0; i < len(c); i++ { | |
r := <-coll | |
if r.ok { | |
out = append(out, r.v) | |
} | |
} | |
return out | |
} | |
type Person struct { | |
Name string | |
Age int | |
} | |
func iPerson(p T) *Person { | |
return p.(*Person) | |
} | |
func main() { | |
people := []interface{}{&Person{"Bob",45}, | |
&Person{"Steve",12}, | |
&Person{"Laura",36}, | |
&Person{"Larry",15}, | |
&Person{"Harry",23}} | |
From(people).pWhere(func (i T) bool { | |
return iPerson(i).Age > 16 | |
}).pDo(func (v T) { | |
fmt.Println(iPerson(v).Name) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment