Created
September 16, 2017 21:47
-
-
Save derrandz/efe989a141319e01fb47e83f7e1640fa to your computer and use it in GitHub Desktop.
js reducer style in go, with interfaces
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
// 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