Skip to content

Commit

Permalink
Fix detection of circular references as opposed to object identity (#7)
Browse files Browse the repository at this point in the history
* Add (failing) test for object identity, refs #5

* Fix detection of circular references, fixes #5

Tests now pass again
  • Loading branch information
MikeRalphson authored and eagleeye committed May 24, 2018
1 parent ff28dd6 commit 0687de9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 9 additions & 3 deletions index.js
Expand Up @@ -32,21 +32,27 @@ function ensureProperties(obj) {

if (typeof obj.toJSON === 'function') {
try {
return visit(obj.toJSON());
var fResult = visit(obj.toJSON());
seen.pop();
return fResult;
} catch(err) {
return throwsMessage(err);
}
}

if (Array.isArray(obj)) {
return obj.map(visit);
var aResult = obj.map(visit);
seen.pop();
return aResult;
}

return Object.keys(obj).reduce(function(result, prop) {
var result = Object.keys(obj).reduce(function(result, prop) {
// prevent faulty defined getter properties
result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
return result;
}, {});
seen.pop();
return result;
};

return visit(obj);
Expand Down
8 changes: 8 additions & 0 deletions test/safe-json-stringify-test.js
Expand Up @@ -8,6 +8,14 @@ test('basic stringify', function(t) {
t.equal('{"foo":"bar"}', safeJsonStringify({foo: 'bar'}), 'a simple object');
});

test('object identity', function(t) {
t.plan(1);

var a = { foo: 'bar' };
var b = { one: a, two: a };
t.equal('{"one":{"foo":"bar"},"two":{"foo":"bar"}}',safeJsonStringify(b),'an object with identical properties');
});

test('circular references', function(t) {
t.plan(2);

Expand Down

0 comments on commit 0687de9

Please sign in to comment.