Skip to content

Commit

Permalink
Add get support for dicts
Browse files Browse the repository at this point in the history
  • Loading branch information
Dean-Coakley committed Oct 2, 2019
1 parent 626db5a commit d4e8594
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
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
1 change: 1 addition & 0 deletions functions.go
Expand Up @@ -256,6 +256,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 d4e8594

Please sign in to comment.