Skip to content

Instantly share code, notes, and snippets.

@derrandz
Created September 16, 2017 21:47
Show Gist options
  • Save derrandz/efe989a141319e01fb47e83f7e1640fa to your computer and use it in GitHub Desktop.
Save derrandz/efe989a141319e01fb47e83f7e1640fa to your computer and use it in GitHub Desktop.
js reducer style in go, with interfaces
// a hack
package main
import "fmt"
type auto interface{}
type reduceClosure func(auto, auto, int, auto) auto
type Reducable interface{
reduce(reduceClosure, auto) auto
}
type stringArray []string
func (strArr stringArray) reduce(fn reduceClosure, acc auto) auto {
for i, v := range strArr {
acc = fn(acc, v, i, strArr)
}
return acc
}
func main() {
var i Reducable
words := stringArray{
"Who", "let", "the", "dogs", "out",
}
i = words
wordsFlatLength := i.reduce(func(acc, word auto, i int, words auto) auto {
xacc, xaccok := acc.(int)
xword, xwordok := word.(string)
if xaccok && xwordok {
return xacc + len(xword)
} else {
return acc
}
}, 0)
fmt.Println("Flat words length:", wordsFlatLength)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment