common/maps: Add Scratch.DeleteInMap
authormeehawk <80167324+meehawk@users.noreply.github.com>
Mon, 17 May 2021 13:45:33 +0000 (19:15 +0530)
committerGitHub <noreply@github.com>
Mon, 17 May 2021 13:45:33 +0000 (15:45 +0200)
Add Scratch.DeleteInMap method. This method works similar to Scratch.SetInMap. It takes in two string parameters, key and mapKey and deletes the value mapped to mapKey in key

Closes #8504

common/maps/scratch.go
common/maps/scratch_test.go
docs/content/en/functions/scratch.md

index ccd03ef3272576b5c09d97d84c5fcbe8bb1bada7..26ffef7d250f86554463f51d10af2a07389a5721 100644 (file)
@@ -129,6 +129,17 @@ func (c *Scratch) SetInMap(key string, mapKey string, value interface{}) string
        return ""
 }
 
+// DeleteInMap deletes a value to a map with the given key in the Node context.
+func (c *Scratch) DeleteInMap(key string, mapKey string) string {
+       c.mu.Lock()
+       _, found := c.values[key]
+       if found {
+               delete(c.values[key].(map[string]interface{}), mapKey)
+       }
+       c.mu.Unlock()
+       return ""
+}
+
 // GetSortedMapValues returns a sorted map previously filled with SetInMap.
 func (c *Scratch) GetSortedMapValues(key string) interface{} {
        c.mu.RLock()
index d893ccb03e7bd6ef055bf6f7fe9698a7949a1b88..96b352572b4fe8a5889c2d49ae0b2270ec60c742 100644 (file)
@@ -188,6 +188,20 @@ func TestScratchSetInMap(t *testing.T) {
        c.Assert(scratch.GetSortedMapValues("key"), qt.DeepEquals, []interface{}{0: "Abc (updated)", 1: "Def", 2: "Lux", 3: "Zyx"})
 }
 
+func TestScratchDeleteInMap(t *testing.T) {
+       t.Parallel()
+       c := qt.New(t)
+
+       scratch := NewScratch()
+       scratch.SetInMap("key", "lux", "Lux")
+       scratch.SetInMap("key", "abc", "Abc")
+       scratch.SetInMap("key", "zyx", "Zyx")
+       scratch.DeleteInMap("key", "abc")
+       scratch.SetInMap("key", "def", "Def")
+       scratch.DeleteInMap("key", "lmn") // Do nothing
+       c.Assert(scratch.GetSortedMapValues("key"), qt.DeepEquals, []interface{}{0: "Def", 1: "Lux", 2: "Zyx"})
+}
+
 func TestScratchGetSortedMapValues(t *testing.T) {
        t.Parallel()
        scratch := NewScratch()
index 10623b2cb3a1da3eec35baaba18aa066f7f2182a..f42b0ad57dd34afd80d335d9934c61875eae99b1 100644 (file)
@@ -97,6 +97,18 @@ Takes a `key`, `mapKey` and `value` and add a map of `mapKey` and `value` to the
 {{ .Scratch.Get "greetings" }} > map[french:Bonjour english:Hello]
 ```
 
+#### .DeleteInMap
+Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
+
+```go-html-template
+{{ .Scratch.SetInMap "greetings" "english" "Hello" }}
+{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }}
+----
+{{ .Scratch.DeleteInMap "greetings" "english" }}
+----
+{{ .Scratch.Get "greetings" }} > map[french:Bonjour]
+```
+
 #### .GetSortedMapValues
 Returns array of values from `key` sorted by `mapKey`