mirror of
https://github.com/toss/es-toolkit.git
synced 2024-12-03 01:42:44 +03:00
1918eec3d9
* feat: Add invert * feat: Add test for invert * feat: Add bench for invert * docs: Add docs for invert * docs: fix .vitepress for invert * chore: Change incorrectly specified path * chore: Refactor benchmark tests * feat: refactor type invert * Update src/object/invert.ts --------- Co-authored-by: Sojin Park <raon0211@gmail.com>
30 lines
769 B
Markdown
30 lines
769 B
Markdown
# invert
|
|
|
|
Creates a new object by swapping the keys and values of the given object.
|
|
|
|
This function takes an object and creates a new object where the keys are the values and the values are the keys of the original object. If there are duplicate values in the input object, the key that appears last will be used as the new key.
|
|
|
|
## Signature
|
|
|
|
```typescript
|
|
function invert<K extends string | number | symbol, V extends string | number | symbol>(
|
|
obj: Record<K, V>
|
|
): { [key in V]: K };
|
|
```
|
|
|
|
### Parameters
|
|
|
|
- `obj` (`Record<K, V>`): The object to invert.
|
|
|
|
### Returns
|
|
|
|
(`{ [key in V]: K }`): A new object with keys and values inverted.
|
|
|
|
## Examples
|
|
|
|
```typescript
|
|
const obj = { a: 1, b: 1, c: 2 };
|
|
const result = invert(obj);
|
|
// result will be { 1: 'b', 2: 'c' }
|
|
```
|