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:
Changwoo Yoo 2024-07-17 22:27:45 +09:00 committed by GitHub
parent 62fafe69a7
commit 1ea74b70af
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 2 deletions

View File

@ -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' });
});
});

View File

@ -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;
}