mirror of
https://github.com/toss/es-toolkit.git
synced 2024-11-28 03:34:26 +03:00
fix(invert): Fixed invert
not to invert inherited properties (#221)
* test: add tests to be compatible with lodash * fix: invert not to invert inherited properties * perf: slightly improve performance by not using for..of * Update src/object/invert.ts --------- Co-authored-by: Sojin Park <raon0211@gmail.com>
This commit is contained in:
parent
62fafe69a7
commit
1ea74b70af
@ -27,4 +27,20 @@ describe('invert', () => {
|
||||
it('should handle objects with duplicate values by keeping the last key', () => {
|
||||
expect(invert({ a: 1, b: 1, c: 2 })).toEqual({ 1: 'b', 2: 'c' });
|
||||
});
|
||||
|
||||
it('should work with values that shadow keys on `Object.prototype`', () => {
|
||||
const object = { a: 'hasOwnProperty', b: 'constructor' };
|
||||
expect(invert(object)).toEqual({ hasOwnProperty: 'a', constructor: 'b' });
|
||||
});
|
||||
|
||||
it('should work with an object that has a `length` property', () => {
|
||||
const object = { 0: 'a', 1: 'b', length: 2 };
|
||||
expect(invert(object)).toEqual({ a: '0', b: '1', 2: 'length' });
|
||||
});
|
||||
|
||||
it('should not invert inherited properties', () => {
|
||||
const object = Object.create({ a: 1 });
|
||||
object.b = 2;
|
||||
expect(invert(object)).toEqual({ 2: 'b' });
|
||||
});
|
||||
});
|
||||
|
@ -19,8 +19,11 @@
|
||||
export function invert<K extends PropertyKey, V extends PropertyKey>(obj: Record<K, V>): { [key in V]: K } {
|
||||
const result = {} as { [key in V]: K };
|
||||
|
||||
for (const key in obj) {
|
||||
const value = obj[key as K] as V;
|
||||
const keys = Object.keys(obj) as K[];
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
const value = obj[key];
|
||||
result[value] = key;
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user