Skip to content

Commit

Permalink
Merge pull request #4 from ungap/issue-3
Browse files Browse the repository at this point in the history
Fix #3 - Avoid collisions
  • Loading branch information
WebReflection authored Oct 15, 2024
2 parents 5516447 + d6dcef4 commit 939ff55
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
28 changes: 14 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,24 @@ if (!rawJSON) {
throw new TypeError('Unexpected ' + type);
};

const { apply } = Reflect;

// parse
const p = parse;
parse = (text, reviver) => {
if (typeof reviver === 'function') {
const $ = reviver;
const context = new Map;
// parse all primitives in one go: string | number | boolean | null
const re = /("(?:(?=(\\?))\2.)*?"\s*:?|[0-9eE.-]+|true|false|null)/g;
let match;
while (match = re.exec(text)) {
const [source] = match;
if (source.at(-1) !== ':') context.set(p(source), { source });
}
reviver = function (key, value) {
const ctx = context.get(value);
return apply($, this, ctx ? [key, value, ctx] : [key, value]);
const a = [];
text = text.replace(
// parse all primitives in one go: string | number | boolean | null
/(?:"(?:(?=(\\?))\1.)*?"\s*:?|[0-9eE.-]+|true|false|null)/g,
$ => $.at(-1) !== ':' ? ($[0] === '"' ? (a.push($) - 1) : `"${$}"`) : $
);
reviver = function (key, source) {
switch (typeof source) {
// abracadabra
case 'number': source = a[source];
case 'string': return $.call(this, key, p(source), { source });
}
return $.call(this, key, source);
};
}
return p(text, reviver);
Expand All @@ -64,7 +64,7 @@ if (!rawJSON) {
const $ = typeof r === 'function' ? r :
(r && isArray(r) ? (k, v) => (!k || r.includes(k) ? v : void 0) : noop);
return function (key, value) {
value = apply($, this, [key, value]);
value = $.call(this, key, value);
if (isRawJSON(value)) {
const { rawJSON } = value;
raws.set(value = `'${++id}'${suffix}`, rawJSON);
Expand Down
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ console.assert(JSON.stringify({ a: 1, b: 2 }, null) === '{"a":1,"b":2}');

console.assert(JSON.stringify({ a: 1, b: 2 }, (_, v) => v) === '{"a":1,"b":2}');

// issue #3 covered
console.log(
JSON.parse('{"a":9007199254740993,"b":9007199254740992}', JSON.reviver),
'{ a: 9007199254740993n, b: 9007199254740992 }'
);

console.log(
JSON.parse('{"a":9007199254740992,"b":9007199254740993}', JSON.reviver),
'{ a: 9007199254740992, b: 9007199254740993n }'
);

// const s = JSON.rawJSON(JSON.stringify('Hello "there"!'));
// JSON.parse(JSON.stringify({ s }), (key, value, context) => { console.log({ key, value, context }); return value });

0 comments on commit 939ff55

Please sign in to comment.