Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(invert): Fixed invert not to invert inherited properties #221

Merged
merged 4 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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' });
});
});
6 changes: 4 additions & 2 deletions src/object/invert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
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];
raon0211 marked this conversation as resolved.
Show resolved Hide resolved
result[value] = key;
}

Expand Down