Created
May 28, 2018 03:11
-
-
Save ezy/0a1afcac18a5ab7f4fb765c19fc2128f to your computer and use it in GitHub Desktop.
Detect which object in a JSON.stringify function is Cyclic
This file contains hidden or 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
| function isCyclic(obj) { | |
| var keys = []; | |
| var stack = []; | |
| var stackSet = new Set(); | |
| var detected = false; | |
| function detect(obj, key) { | |
| if (typeof obj != 'object') { return; } | |
| if (stackSet.has(obj)) { // it's cyclic! Print the object and its locations. | |
| var oldindex = stack.indexOf(obj); | |
| var l1 = keys.join('.') + '.' + key; | |
| var l2 = keys.slice(0, oldindex + 1).join('.'); | |
| console.log('CIRCULAR: ' + l1 + ' = ' + l2 + ' = ' + obj); | |
| console.log(obj); | |
| detected = true; | |
| return; | |
| } | |
| keys.push(key); | |
| stack.push(obj); | |
| stackSet.add(obj); | |
| for (var k in obj) { //dive on the object's children | |
| if (obj.hasOwnProperty(k)) { detect(obj[k], k); } | |
| } | |
| keys.pop(); | |
| stack.pop(); | |
| stackSet.delete(obj); | |
| return; | |
| } | |
| detect(obj, 'obj'); | |
| return detected; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment