Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add splitToMap #359

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/dicts.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,14 @@ system when there is an error.
dict "a" 1 "b" 2 | deepCopy
```

### `splitToMap`

Splits the given string on the provided separator and splits each resulting item into a key and value:

```golang
{{ "foo:bar\nbaz:bat\n" | splitToMap "\n" ":" }}
```

## A Note on Dict Internals

A `dict` is implemented in Go as a `map[string]interface{}`. Go developers can
Expand Down
2 changes: 2 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ var genericMap = map[string]interface{}{
// splitn "/" foo/bar/fuu returns map[int]string{0: foo, 1: bar/fuu}
"splitn": splitn,
"toStrings": strslice,
// splitToMap returns map[string]string
"splitToMap": splitToMap,

"until": until,
"untilStep": untilStep,
Expand Down
20 changes: 20 additions & 0 deletions strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,26 @@ func splitn(sep string, n int, orig string) map[string]string {
return res
}

// splitToMap is a version of strings.Split which splits a second time for each
// item in the slice generated from the first split, building a map
func splitToMap(sep1, sep2, s string) (map[string]string, error) {
s = strings.TrimSpace(s)
if s == "" {
emptyMap := make(map[string]string)
return emptyMap, nil
}
s1 := strings.Split(s, sep1)
m := make(map[string]string, len(s1))
for i := range s1 {
k, v, f := strings.Cut(s1[i], sep2)
if !f {
continue
}
m[k] = v
}
return m, nil
}

// substring creates a substring of the given string.
//
// If start is < 0, this calls string[:end].
Expand Down