Skip to content

Commit

Permalink
[Fix] stringify: cyclic reference
Browse files Browse the repository at this point in the history
  • Loading branch information
liaokunhua committed Dec 4, 2021
1 parent 24c19cc commit ec25fbd
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
|| typeof v === 'bigint';
};

var scSym = Symbol('SideChannel');

var stringify = function stringify(
object,
prefix,
Expand All @@ -75,8 +77,23 @@ var stringify = function stringify(
) {
var obj = object;

if (sideChannel.has(object)) {
throw new RangeError('Cyclic object value');
var tmpSc = sideChannel;
var step = 0;
var findFlag = false;
while ((tmpSc = tmpSc.get(scSym)) !== undefined && !findFlag) {
// Where object last appeared in the ref tree
var pos = tmpSc.get(object);
step += 1;
if (pos != undefined) {
if (pos === step) {
throw new RangeError('Cyclic object value');
} else {
findFlag = true; // Break while
}
}
if (tmpSc.get(scSym) === undefined) {
step = 0;
}
}

if (typeof filter === 'function') {
Expand Down Expand Up @@ -145,8 +162,9 @@ var stringify = function stringify(
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
: prefix + (allowDots ? '.' + key : '[' + key + ']');

sideChannel.set(object, true);
sideChannel.set(object, step);
var valueSideChannel = getSideChannel();
valueSideChannel.set(scSym, sideChannel);
pushToArray(values, stringify(
value,
keyPrefix,
Expand Down

0 comments on commit ec25fbd

Please sign in to comment.