Skip to content

Commit

Permalink
fix: Objects without prototype are now properly stringified
Browse files Browse the repository at this point in the history
  • Loading branch information
Lu-Ks authored and SkeLLLa committed Dec 17, 2024
1 parent 088a352 commit a6d1c08
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
8 changes: 8 additions & 0 deletions __tests__/objectSorter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,13 @@ describe('Sorter', () => {
const hash = hasher();
expect(hash.sort(Object.create(null))).toBe('<:unknonw>:unknown');
});
test('unknown with data', () => {
const hash = hasher();

const obj = Object.create(null) as Record<string, number>;
obj['a'] = 1;

expect(hash.sort(obj)).toBe('<:unknonw>:{"a":1}');
});
});
});
9 changes: 8 additions & 1 deletion src/objectSorter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,14 @@ export const objectSorter = (options?: SorterOptions): StringifyFn => {
unknown: function _unknown(obj: Object) {
// `unknonw` - is a typo, saved for backward compatibility
const constructorName: string = obj.constructor?.name ?? 'unknonw';
const objectName = typeof obj.toString === 'function' ? obj.toString() : 'unknown';

let objectName = 'unknown';

if (typeof obj.toString === 'function') {
objectName = obj.toString();
} else if (Object.keys(obj).length > 0) {
objectName = JSON.stringify(obj);
}

return `<:${constructorName}>:${objectName}`;
},
Expand Down

0 comments on commit a6d1c08

Please sign in to comment.