Skip to content

Instantly share code, notes, and snippets.

@azihsoyn
Created July 4, 2018 16:32
Show Gist options
  • Save azihsoyn/7424681ce47f133c0d4e69d153d32a61 to your computer and use it in GitHub Desktop.
Save azihsoyn/7424681ce47f133c0d4e69d153d32a61 to your computer and use it in GitHub Desktop.
go collection map
package main
import (
"fmt"
"github.com/kr/pretty"
)
type IntList []int
type T interface{}
type R interface{}
type Mapper interface {
Map(func(T) R) Mapper
Append(T) Mapper
}
var newFuncs = []func(v T) (Mapper, bool){
newStringList,
newIntList,
}
func NewList(v T) Mapper {
for _, f := range newFuncs {
if mapper, ok := f(v); ok {
return mapper
}
}
return nil
}
type StringList []string
func (ss StringList) Append(in T) Mapper {
return append(ss, in.(string))
}
func newStringList(v T) (Mapper, bool) {
switch v.(type) {
case string:
return make(StringList, 0), true
default:
return nil, false
}
}
func newIntList(v T) (Mapper, bool) {
switch v.(type) {
case int:
return make(IntList, 0), true
default:
return nil, false
}
}
func (ss StringList) Map(f func(in T) R) Mapper {
var ret Mapper
for _, s := range ss {
r := f(s)
if ret == nil {
ret = NewList(r)
}
if ret != nil {
ret = ret.Append(r)
}
}
return ret
}
func (is IntList) Map(f func(in T) R) Mapper {
var ret Mapper
for _, i := range is {
r := f(i)
if ret == nil {
ret = NewList(r)
}
if ret != nil {
ret = ret.Append(r)
}
}
return ret
}
func (is IntList) Append(in T) Mapper {
return append(is, in.(int))
}
func main() {
ret := IntList{1, 2, 3, 4, 5}.
Map(func(in T) R {
return fmt.Sprintf("No. %d", in.(int))
}).
Map(func(in T) R {
return fmt.Sprintf("This string is %s", in.(string))
})
pretty.Println(ret)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment