Just like javascript's map
Mapis done on sequentiallyParallelMap- is done concurrently using go routine on each entry
- will be faster on large amount of data with slow
map/transformation
func Map(arr interface{}, transform interface{}) (interface{}, error)arr interface{}have to be either array or slice of somethingtransform interface{}have to be afuncthat accepts element type ofarrand returns either a new type, or the same as element type ofarr
interface{}is a slice of the return type oftransformerrorifarris not array or slicetransformis nil or not a function
source := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
addOne := func(num int) int {
time.Sleep(50 * time.Millisecond) //simulate slow operation
return num+1
}
start := time.Now()
resultMap, err := arrayutil.Map(source, addOne)
fmt.Println("SRC:", source)
fmt.Println("RES:", resultMap.([]int))
fmt.Println("ERR:", err)
fmt.Println("DUR:", float64(time.Since(start).Nanoseconds())/1000000., "ms")
//SRC: [1 2 3 4 5 6 7 8 9 10]
//RES: [2 3 4 5 6 7 8 9 10 11]
//ERR: <nil>
//DUR: 536.282464 ms
start = time.Now()
resultPMap, err := arrayutil.ParallelMap(source, addOne)
fmt.Println("SRC:", source)
fmt.Println("RES:", resultPMap.([]int))
fmt.Println("ERR:", err)
fmt.Println("DUR:", float64(time.Since(start).Nanoseconds())/1000000., "ms")
//SRC: [1 2 3 4 5 6 7 8 9 10]
//RES: [2 3 4 5 6 7 8 9 10 11]
//ERR: <nil>
//DUR: 54.597015 msJust like javascript's reduce
func Reduce(arr interface{}, initialValue interface{}, transform interface{}) (interface{}, error)arr interface{}have to be either array or slice of somethinginitialValue interface{}initial value of the reduce resulttransform interface{}reducer function- Must accepts 3 parameters
accumulatorin which type must be the same ofinitialValuetypeentryin which type must be the same ofarrelement typeidxinteger index
- And returns
Tin whichTis the type ofinitialValue
- Must accepts 3 parameters
interface{}is the return type oftransformerrorifarris not array or slicetransformis nil or not a function
source := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum := func(accumulator, entry, _ int) int {
return accumulator + entry
}
result, err := arrayutil.Reduce(source, 0, sum)
fmt.Println("SRC:", source)
fmt.Println("RES:", result.(int))
fmt.Println("ERR:", err)
//SRC: [1 2 3 4 5 6 7 8 9 10]
//RES: 55
//ERR: <nil>