Skip to content

Commit

Permalink
Merge pull request #78 from Rich-Harris/ignore-non-enumerable-symbols
Browse files Browse the repository at this point in the history
ignore non-enumerable symbols
  • Loading branch information
Rich-Harris authored Apr 19, 2024
2 parents 7bbc088 + 1c50e79 commit 686287c
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/stringify.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
DevalueError,
enumerable_symbols,
get_type,
is_plain_object,
is_primitive,
Expand Down Expand Up @@ -143,7 +144,7 @@ export function stringify(value, reducers) {
);
}

if (Object.getOwnPropertySymbols(thing).length > 0) {
if (enumerable_symbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys
Expand Down
3 changes: 2 additions & 1 deletion src/uneval.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
DevalueError,
enumerable_symbols,
escaped,
get_type,
is_plain_object,
Expand Down Expand Up @@ -89,7 +90,7 @@ export function uneval(value, replacer) {
);
}

if (Object.getOwnPropertySymbols(thing).length > 0) {
if (enumerable_symbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys
Expand Down
7 changes: 7 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,10 @@ export function stringify_string(str) {

return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
}

/** @param {Record<string | symbol, any>} object */
export function enumerable_symbols(object) {
return Object.getOwnPropertySymbols(object).filter(
(symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable
);
}
13 changes: 13 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,19 @@ const fixtures = {
assert.equal(Object.getPrototypeOf(value), Object.prototype);
assert.equal(Object.keys(value).length, 0);
}
},
{
name: 'non-enumerable symbolic key',
value: (() => {
const obj = { x: 1 };
Object.defineProperty(obj, Symbol('key'), {
value: 'value',
enumerable: false
});
return obj;
})(),
js: '{x:1}',
json: '[{"x":1},1]'
}
],

Expand Down

0 comments on commit 686287c

Please sign in to comment.