Accumulate

Introduction

Implement the accumulate operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection.

Given the collection of strings:

  • "cat", "Dog", "b4t", "gO"

And the operation:

  • upcase a string

Your code should be able to produce the collection of strings:

  • "CAT", "DOG", "B4T, "GO"

Check out the test suite to see the expected function signature.

package accumulate

// Accumulate change slice content base on the converter
func Accumulate(s []string, converter func(string) string) []string {
	result := s
	for i, r := range s {
		result[i] = converter(r)
	}
	return result
}

Point

  • If you defined return value in func definition, you don't need declare return variable in return clause

  • out is a slice, use append to add value. not out[0] = s

Other solution would also work and looks simpler. But it has a worse performance than my solution.

version1.0

BenchmarkAccumulate-8 10000000 183 ns/op 0 B/op 0 allocs/op

Other

BenchmarkAccumulate-8 2000000 961 ns/op 344 B/op 18 allocs/op

Last updated