Skip to content

Commit

Permalink
Detect cycles during development (see rtfeldman#73 and rtfeldman#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
shamrin committed Apr 6, 2016
1 parent a11878c commit a46e934
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/seamless-immutable.js
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@
return makeImmutable(obj, mutatingObjectMethods);
}

function Immutable(obj, options) {
function Immutable(obj, options, level) {
if (isImmutable(obj)) {
return obj;
} else if (obj instanceof Array) {
Expand All @@ -486,9 +486,21 @@
instantiatePlainObject : (function() { return Object.create(prototype); });
var clone = instantiateEmptyObject();

if (process.env.NODE_ENV !== "production") {
if (level === undefined) {
level = 0;
}
if (level >= 64) {
throw new ImmutableError("Attempt to construct Immutable from a deeply nested object was detected." +
" Have you tried to wrap an object with circular references (e.g. React Component)?" +
" See https://github.com/rtfeldman/seamless-immutable/issues/73 for details.");
}
level += 1;
}

for (var key in obj) {
if (Object.getOwnPropertyDescriptor(obj, key)) {
clone[key] = Immutable(obj[key]);
clone[key] = Immutable(obj[key], undefined, level);
}
}

Expand Down
11 changes: 11 additions & 0 deletions test/Immutable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ var getTestUtils = require("./TestUtils.js");
});
});
});

it("detects cycles", function() {
var obj = {};
obj.prop = obj;

if (config.id === 'prod') {
assert.throws(function() { Immutable(obj); }, RangeError);
} else {
assert.throws(function() { Immutable(obj); }, /deeply nested/);
}
});
});
});
});

0 comments on commit a46e934

Please sign in to comment.