hugolib: Add Reset method to delete key from Scratch
authorcmal <paul@cmal.info>
Fri, 16 Mar 2018 23:13:23 +0000 (00:13 +0100)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 16 Mar 2018 23:13:23 +0000 (00:13 +0100)
docs/content/functions/scratch.md
hugolib/scratch.go
hugolib/scratch_test.go

index a827db54355bf6f71fc366073bff3ee51ca6a748..b8fc0e59ce02ca445bda4a9523e7a35c5101a4f1 100644 (file)
@@ -32,6 +32,7 @@ See [this Go issue](https://github.com/golang/go/issues/10608) for the main moti
 * `Get` returns the `value` for the `key` given.
 * `SetInMap` takes a `key`, `mapKey` and `value`
 * `GetSortedMapValues` returns array of values from `key` sorted by `mapKey`
+* `Delete` takes a `key` to remove
 
 `Set` and `SetInMap` can store values of any type.
 
@@ -69,6 +70,11 @@ The usage is best illustrated with some samples:
 {{ $.Scratch.SetInMap "a3" "c" "CC" }}
 {{ $.Scratch.SetInMap "a3" "b" "BB" }}
 {{ $.Scratch.GetSortedMapValues "a3" }} {{/* => []interface {}{"AA", "BB", "CC"} */}}
+
+{{ $.Scratch.Add "a" 1 }}
+{{ $.Scratch.Delete "a" }}
+{{ $.Scratch.Add "a" 2 }}
+{{ $.Scratch.Get "a" }} {{/* => 2 */}}
 ```
 
 {{% note %}}
index ca2c9d6a8c87f5427ca67a96e5e1f8f300569d50..37ed5df35be1a4a615ef0c9e02fd219eb1aecbd9 100644 (file)
@@ -73,6 +73,14 @@ func (c *Scratch) Set(key string, value interface{}) string {
        return ""
 }
 
+// Reset deletes the given key
+func (c *Scratch) Delete(key string) string {
+       c.mu.Lock()
+       delete(c.values, key)
+       c.mu.Unlock()
+       return ""
+}
+
 // Get returns a value previously set by Add or Set
 func (c *Scratch) Get(key string) interface{} {
        c.mu.RLock()
index f65c2ddfe43a5a11579a75305544a182c91b48ae..5ec2b89c8c037a8f1a3bfb93ce5226988f1c16ca 100644 (file)
@@ -87,6 +87,15 @@ func TestScratchSet(t *testing.T) {
        assert.Equal(t, "val", scratch.Get("key"))
 }
 
+func TestScratchDelete(t *testing.T) {
+       t.Parallel()
+       scratch := newScratch()
+       scratch.Set("key", "val")
+       scratch.Delete("key")
+       scratch.Add("key", "Lucy Parsons")
+       assert.Equal(t, "Lucy Parsons", scratch.Get("key"))
+}
+
 // Issue #2005
 func TestScratchInParallel(t *testing.T) {
        var wg sync.WaitGroup