Created
June 4, 2015 02:41
-
-
Save sbstp/e63625d7bf20f3731c11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('lib/test'); | |
// Circular reference detection. | |
function checkCircularRefs(obj, parents) | |
{ | |
var val; | |
parents = parents || []; | |
for (var key in obj) | |
{ | |
if (!obj.hasOwnProperty(key)) continue; | |
var val = obj[key]; | |
if (typeof(val) === 'object') { | |
if (parents.indexOf(val) !== -1) | |
{ | |
throw new Error("Circular reference detected"); | |
} | |
parents.push(val); | |
checkCircularRefs(val, parents); | |
parents.pop(); | |
} | |
} | |
} | |
// should throw | |
assertThrows(function () { | |
var a = []; | |
a.push(a); | |
checkCircularRefs(a); | |
}); | |
// should not throw | |
(function () { | |
var a = [], | |
b = [], | |
c = [], | |
d = [], | |
e = []; | |
g = []; | |
a.push(b, c); | |
b.push(d, e); | |
c.push(g); | |
d.push(c, g); | |
checkCircularRefs(a); | |
})(); | |
// should throw | |
assertThrows(function () { | |
var a = [], | |
b = [], | |
c = [], | |
d = [], | |
e = []; | |
g = []; | |
a.push(b, c); | |
b.push(d, e); | |
c.push(g); | |
d.push(a); | |
checkCircularRefs(a); | |
}); | |
// 2nd paragraph | |
// should not throw | |
(function () { | |
var a = [], | |
b = [], | |
c = [], | |
d = [], | |
e = []; | |
g = []; | |
a.push(b, c); | |
b.push(d, e); | |
c.push(g); | |
g.push(d); | |
checkCircularRefs(a); | |
})(); | |
// should throw | |
assertThrows(function () { | |
var a = [], | |
b = [], | |
c = [], | |
d = [], | |
e = []; | |
g = []; | |
a.push(b, c); | |
b.push(d, e); | |
c.push(g); | |
d.push(a); | |
g.push(d); | |
checkCircularRefs(a); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment