Skip to content

Commit

Permalink
fix(invert): Fixed invert not to invert inherited properties (toss#221
Browse files Browse the repository at this point in the history
)

* 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>
  • Loading branch information
2 people authored and seungrodotlee committed Jul 18, 2024
1 parent 1d5269d commit 477dc8a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/object/invert.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
});
});
7 changes: 5 additions & 2 deletions src/object/invert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit 477dc8a

Please sign in to comment.