I am a JavaScript programmer beginning with Go. I tried to replicate filter and map functions like JavaScript's, as an exercise.
Here is what I came up with.
The filter function:
func Filter(slice interface{}, cb func(i interface{}) bool) []interface{}{
sliceValues := reflect.ValueOf(slice)
newSlice := []interface{}{}
for i := 0; i < sliceValues.Len(); i++{
v := sliceValues.Index(i).Interface()
passed := cb(v)
if passed{
newSlice = append(newSlice, v)
}
}
return newSlice
}
Usage:
a := []int {1,2,3}
result := Filter(a,func(i interface{}) bool{
v,_:= i.(int)
return v > 1
})
fmt.Println(result) // [2 3]
The map function:
func Map(slice interface{}, cb func(i interface{}) interface{}) []interface{}{
sliceValues := reflect.ValueOf(slice)
newSlice := []interface{}{}
for i := 0; i < sliceValues.Len(); i++{
v := sliceValues.Index(i).Interface()
modifiedValue := cb(v)
newSlice = append(newSlice, modifiedValue)
}
return newSlice
}
Usage:
a := []int {1,2,3}
result := Map(a,func(i interface{}) interface{}{
v,_:= i.(int)
return v + 1
})
fmt.Println(result) // [2 3 4]