-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
38 lines (33 loc) · 1009 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var Node = require('./lib/node')
module.exports = isCircular
/**
* checks whether the object is circular
* @param {object} obj - object to check circularity for
* @return {Boolean} true if obj is circular, false if it is not
*/
function isCircular (obj) {
if (!(obj instanceof Object)) {
throw new TypeError('"obj" must be an object (or inherit from it)')
}
return _isCircular(obj)
}
/**
* @private
* checks whether the object is circular
* @param {object} obj - object to check circularity for
* @param {Node} parentList - linked-list that contains all the object's parents
* @return {Boolean} true if obj is circular, false if it is not
*/
function _isCircular (obj, parentList) {
parentList = new Node(obj, parentList)
// breadth-first search for circular object
for (var key in obj) {
var val = obj[key]
if (val instanceof Object) {
if (parentList.contains(val) || _isCircular(val, parentList)) {
return true
}
}
}
return false
}