Created
October 28, 2015 18:21
-
-
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
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 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