Created
July 24, 2016 14:31
-
-
Save petomalina/1e6d45e97e27c782b78f52c32784800d to your computer and use it in GitHub Desktop.
Map, Filter and Reduce above collection of T in Golang
This file contains 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 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