Skip to content

Commit

Permalink
better key stringification
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Sep 25, 2024
1 parent 0c35c0e commit cf76164
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
get_type,
is_plain_object,
is_primitive,
stringify_key,
stringify_string
} from './utils.js';
import {
Expand Down Expand Up @@ -154,7 +155,7 @@ export function stringify(value, reducers) {
if (Object.getPrototypeOf(thing) === null) {
str = '["null"';
for (const key in thing) {
keys.push(`.${key}`);
keys.push(stringify_key(key));
str += `,${stringify_string(key)},${flatten(thing[key])}`;
keys.pop();
}
Expand All @@ -165,7 +166,7 @@ export function stringify(value, reducers) {
for (const key in thing) {
if (started) str += ',';
started = true;
keys.push(`.${key}`);
keys.push(stringify_key(key));
str += `${stringify_string(key)}:${flatten(thing[key])}`;
keys.pop();
}
Expand Down
3 changes: 2 additions & 1 deletion src/uneval.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
get_type,
is_plain_object,
is_primitive,
stringify_key,
stringify_string
} from './utils.js';

Expand Down Expand Up @@ -98,7 +99,7 @@ export function uneval(value, replacer) {
}

for (const key in thing) {
keys.push(`.${key}`);
keys.push(stringify_key(key));
walk(thing[key]);
keys.pop();
}
Expand Down
7 changes: 7 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,10 @@ export function enumerable_symbols(object) {
(symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable
);
}

const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;

/** @param {string} key */
export function stringify_key(key) {
return is_identifier.test(key) ? '.' + key : '[' + JSON.stringify(key) + ']';
}
4 changes: 2 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -584,13 +584,13 @@ for (const fn of [uneval, stringify]) {
class Whatever {}
fn({
foo: {
map: new Map([['key', new Whatever()]])
['string-key']: new Map([['key', new Whatever()]])
}
});
} catch (e) {
assert.equal(e.name, 'DevalueError');
assert.equal(e.message, 'Cannot stringify arbitrary non-POJOs');
assert.equal(e.path, '.foo.map.get("key")');
assert.equal(e.path, '.foo["string-key"].get("key")');
}
});

Expand Down

0 comments on commit cf76164

Please sign in to comment.