Skip to content

Instantly share code, notes, and snippets.

@ches
Created October 28, 2015 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ches/cbbb41edfb72dd4475c3 to your computer and use it in GitHub Desktop.
Save ches/cbbb41edfb72dd4475c3 to your computer and use it in GitHub Desktop.
A quick untyped map & filter example for Go. Author unknown, source: http://play.golang.org/p/yU6KUS1y5w
package main
import "fmt"
type MapFunc func(interface{}) interface{}
type FilterFunc func(interface{}) bool
type Collection []interface{}
type User string
type Host string
func main() {
c := Collection{User("A"), Host("Z"), User("B"), User("A"), Host("Y")}
fmt.Println(c.Filter(ByUser("A")).Map(RenameUser("A", "C")))
}
func (c Collection) Map(fn MapFunc) Collection {
d := make(Collection, 0, len(c))
for _, c := range c {
d = append(d, fn(c))
}
return d
}
func (c Collection) Filter(fn FilterFunc) Collection {
d := make(Collection, 0)
for _, c := range c {
if fn(c) {
d = append(d, c)
}
}
return d
}
func ByUser(u User) FilterFunc {
return func(v interface{}) bool {
if w, ok := v.(User); ok && w == u {
return true
}
return false
}
}
func RenameUser(oldu, newu User) MapFunc {
return func(v interface{}) interface{} {
if w, ok := v.(User); ok && w == oldu {
return newu
}
return v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment