Skip to content

Commit

Permalink
Do not throw error if alterFunc does not change the original key (#249
Browse files Browse the repository at this point in the history
)

* Do not throw error if alterfunc does not change the key

* test case explanation

* Update mapstr/mapstr_test.go

Co-authored-by: Denis <[email protected]>

* update

---------

Co-authored-by: Denis <[email protected]>
  • Loading branch information
khushijain21 and rdner authored Nov 4, 2024
1 parent 038fdc1 commit 7a31e0f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
10 changes: 8 additions & 2 deletions mapstr/mapstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ func (m M) AlterPath(path string, mode TraversalMode, alterFunc AlterFunc) (err
if newKey == "" {
return fmt.Errorf("replacement key for %q cannot be empty", key)
}

// if altered key is equal to the original key, skip below delete/put func
if newKey == key {
return nil
}

_, exists := level[newKey]
if exists {
return fmt.Errorf("replacement key %q already exists: %w", newKey, ErrKeyCollision)
Expand Down Expand Up @@ -271,7 +277,7 @@ func (m M) Traverse(path string, mode TraversalMode, visitor TraversalVisitor) (

for i, segment := range segments {
if !found {
return ErrKeyNotFound
return fmt.Errorf("could not fetch value for key: %s, Error: %w ", path, ErrKeyNotFound)
}
found = false

Expand Down Expand Up @@ -316,7 +322,7 @@ func (m M) Traverse(path string, mode TraversalMode, visitor TraversalVisitor) (
}

if !found {
return ErrKeyNotFound
return fmt.Errorf("could not fetch value for key: %s, Error: %w", path, ErrKeyNotFound)
}

return nil
Expand Down
16 changes: 16 additions & 0 deletions mapstr/mapstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,22 @@ func TestAlterPath(t *testing.T) {
},
},
},
{
name: "does not return an error if alterFunc returns the key unchanged",
from: "level1_field1.key",
mode: CaseInsensitiveMode,
alterFunc: lower,
m: M{
"level1_field1": M{
"Key": "value1",
},
},
exp: M{
"level1_field1": M{ //first level is unchanged - already in lowercase
"key": "value1",
},
},
},
{
name: "alters keys on all nested levels with case-insensitive matching",
from: "level1_field1.level2_field1.level3_field1",
Expand Down

0 comments on commit 7a31e0f

Please sign in to comment.