Skip to content

Commit

Permalink
Merge pull request #197 from Dean-Coakley/get-dict-value
Browse files Browse the repository at this point in the history
Add `get` support to dicts
  • Loading branch information
mattfarina committed Oct 2, 2019
2 parents bee6f49 + 3c81995 commit bd7cb37
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 1 deletion.
7 changes: 7 additions & 0 deletions dict.go
Expand Up @@ -5,6 +5,13 @@ import (
"github.com/mitchellh/copystructure"
)

func get(d map[string]interface{}, key string) interface{} {
if val, ok := d[key]; ok {
return val
}
return ""
}

func set(d map[string]interface{}, key string, value interface{}) map[string]interface{} {
d[key] = value
return d
Expand Down
13 changes: 13 additions & 0 deletions dict_test.go
Expand Up @@ -111,6 +111,19 @@ func TestOmit(t *testing.T) {
}
}

func TestGet(t *testing.T) {
tests := map[string]string{
`{{- $d := dict "one" 1 }}{{ get $d "one" -}}`: "1",
`{{- $d := dict "one" 1 "two" "2" }}{{ get $d "two" -}}`: "2",
`{{- $d := dict }}{{ get $d "two" -}}`: "",
}
for tpl, expect := range tests {
if err := runt(tpl, expect); err != nil {
t.Error(err)
}
}
}

func TestSet(t *testing.T) {
tpl := `{{- $d := dict "one" 1 "two" 222222 -}}
{{- $_ := set $d "two" 2 -}}
Expand Down
13 changes: 13 additions & 0 deletions docs/dicts.md
Expand Up @@ -20,6 +20,19 @@ The following creates a dictionary with three items:
$myDict := dict "name1" "value1" "name2" "value2" "name3" "value 3"
```

## get

Given a map and a key, get the value from the map.

```
get $myDict "key1"
```

The above returns `"value1"`

Note that if the key is not found, this operation will simply return `""`. No error
will be generated.

## set

Use `set` to add a new key/value pair to a dictionary.
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Expand Up @@ -10,7 +10,7 @@ The Sprig library provides over 70 template functions for Go's template language
- [Defaults Functions](defaults.md): `default`, `empty`, `coalesce`, `toJson`, `toPrettyJson`, `toRawJson`, `ternary`
- [Encoding Functions](encoding.md): `b64enc`, `b64dec`, etc.
- [Lists and List Functions](lists.md): `list`, `first`, `uniq`, etc.
- [Dictionaries and Dict Functions](dicts.md): `dict`, `hasKey`, `pluck`, `deepCopy`, etc.
- [Dictionaries and Dict Functions](dicts.md): `get`, `set`, `dict`, `hasKey`, `pluck`, `deepCopy`, etc.
- [Type Conversion Functions](conversion.md): `atoi`, `int64`, `toString`, etc.
- [File Path Functions](paths.md): `base`, `dir`, `ext`, `clean`, `isAbs`
- [Flow Control Functions](flow_control.md): `fail`
Expand Down
1 change: 1 addition & 0 deletions functions.go
Expand Up @@ -258,6 +258,7 @@ var genericMap = map[string]interface{}{
"tuple": list, // FIXME: with the addition of append/prepend these are no longer immutable.
"list": list,
"dict": dict,
"get": get,
"set": set,
"unset": unset,
"hasKey": hasKey,
Expand Down

0 comments on commit bd7cb37

Please sign in to comment.