Created
February 4, 2018 04:49
-
-
Save srishanbhattarai/1cf2d0289270cbc356b61bc2b7036c9e to your computer and use it in GitHub Desktop.
Interpolate strings in curly braces with a map.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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