Skip to content

Commit

Permalink
add rename() to Mappable
Browse files Browse the repository at this point in the history
  • Loading branch information
MZanggl committed Feb 16, 2021
1 parent 5c30397 commit 429fb24
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,16 @@ given.map({ strings: 2, numbers: 1, functions: 4 })
.keys() // ['numbers', 'functions', 'strings']
```

### rename

Renames the given key with the new key if found, keeping the original insertion order.

```javascript
given.map({ one: 1, to: 2, three: 3 })
.rename('to', 'two')
.keys() // ['one', 'two', 'three']
```

## Numbers

<small>
Expand Down
9 changes: 9 additions & 0 deletions src/objects/Mappable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ class Mappable<K = any, V = any> extends Map<K, V> {
.toMap()
}

/**
* Renames the given key with the new key if found, keeping the original insertion order.
*/
rename(oldKey: K, newKey: K) {
return this.mapKeys((_, key) => {
return (key === oldKey) ? newKey : key
})
}

/**
* Iterates the entries through the given callback and assigns each result as the value.
*/
Expand Down
8 changes: 8 additions & 0 deletions test/mappable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,12 @@ test('only() returns a new map with only the given keys', assert => {
test('except() returns a new map with all keys except for the given keys', assert => {
const map = given.map({ one: 1, two: 2, three: 3 }).except(['one', 'two'])
assert.deepEqual(map.keys(), ['three'])
})

test('rename() renames a key if found', assert => {
const map = given.map({ one: 1, to: 2, three: 3 }).rename('to', 'two')
assert.deepEqual(map.keys(), ['one', 'two', 'three'])

const map2 = given.map({ one: 1, two: 2, three: 3 }).rename('for', 'four')
assert.deepEqual(map2.keys(), ['one', 'two', 'three'])
})

0 comments on commit 429fb24

Please sign in to comment.