Skip to content

Instantly share code, notes, and snippets.

@srishanbhattarai
Created February 4, 2018 04:49
Show Gist options
  • Save srishanbhattarai/1cf2d0289270cbc356b61bc2b7036c9e to your computer and use it in GitHub Desktop.
Save srishanbhattarai/1cf2d0289270cbc356b61bc2b7036c9e to your computer and use it in GitHub Desktop.
Interpolate strings in curly braces with a map.
package util
import "strings"
// Interpolate replaces the values in the input string
// inside parentheses with the params supplied.
// Example:
// Interpolate("/{owner}/{repo}", map[string]string{"owner: "golang", "repo": "go"})
// Returns:
// "/golang/go"
func Interpolate(str string, values map[string]string) string {
formattedStr := str
for k, v := range values {
t := "{" + k + "}"
formattedStr = strings.Replace(formattedStr, t, v, -1)
}
return formattedStr
}
package util
import (
"testing"
"github.com/magiconair/properties/assert"
)
func TestInterpolate(t *testing.T) {
tt := []struct {
name string
str string
expected string
val map[string]string
}{
{
"Should interpolate the value",
"Hello {adjective} world",
"Hello cruel world",
map[string]string{
"adjective": "cruel",
},
},
{
"Should interpolate multiple values",
"/{owner}/{repo}/",
"/golang/go/",
map[string]string{
"owner": "golang",
"repo": "go",
},
},
{
"Should ignore all absent values",
"Hello {adjective} world {punctuation}",
"Hello cruel world {punctuation}",
map[string]string{
"adjective": "cruel",
},
},
}
for _, test := range tt {
t.Run(test.name, func(t *testing.T) {
formattedStr := Interpolate(test.str, test.val)
assert.Equal(t, formattedStr, test.expected)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment