Skip to content

Instantly share code, notes, and snippets.

@petomalina
Created July 24, 2016 14:31
Show Gist options
  • Save petomalina/1e6d45e97e27c782b78f52c32784800d to your computer and use it in GitHub Desktop.
Save petomalina/1e6d45e97e27c782b78f52c32784800d to your computer and use it in GitHub Desktop.
Map, Filter and Reduce above collection of T in Golang
package operations
type T struct {
Code int
}
type TSequence []*T
type TMapFunc func(t *T) *T
type TFilterFunc func(t *T) bool
type TReduceFunc func(first *T, second *T) *T
func (seq TSequence) Map(mapper TMapFunc) TSequence {
res := []*T{}
for _, val := range seq {
res = append(res, mapper(val))
}
return res
}
func (seq TSequence) Filter(filter TFilterFunc) TSequence {
res := []*T{}
for _, val := range seq {
if filter(val) {
res = append(res, val)
}
}
return res
}
func (seq TSequence) Reduce(reducer TReduceFunc, init *T) *T {
// initialize current value (first)
curr := init
// go over all values
for _, val := range seq {
curr = reducer(curr, val)
}
return curr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment