Ding-Log
  • Ding Blog
  • Life
    • My Tool Box
  • Golang
    • Basic
      • Go语言学习笔记
        • Go语言 Channel
        • Go语言 goroutine
        • Go语言 如何写Godoc
        • Go语言panic, recover
        • Go语言的Defer函数
        • Go语言的闭包
        • Go语言接口(Golang - Interface)
        • Go语言的面向对象
      • Go语言爬虫
        • Go语言爬虫 - 广度优先算法
      • Map
    • Web
      • Example to handle GET and POST request in Golang
    • Exercism
      • Isogram
      • ETL
      • Accumulate
      • Scrabble Score
  • SAP
    • SAPUI5&Fiori
      • How to prepare C_FIORDEV_20 SAP Certified Development Associate — SAP Fiori Application Developer
      • SAPUI5 sap.ui.define and sap.ui.require
      • SAPUI5 Models and Binding
      • SAPUI5 MVC Walkthrough
    • ABAP
      • Working with Internal Tables
      • 关于使用内部表的时候的一些注意事项
      • Error Handling
  • Log
Powered by GitBook
On this page
  • Introduction
  • Point

Was this helpful?

  1. Golang
  2. Exercism

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
}
package accumulate

type Converter func(string) string

func Accumulate(in []string, cn Converter) (out []string) {
	for _, s := range in {
		out = append(out, cn(s))
	}
	return
}

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

PreviousETLNextScrabble Score

Last updated 6 years ago

Was this helpful?