DEV Community

Suvadeep Majumdar
Suvadeep Majumdar

Posted on

Object, cyclic or not?

This post is about creating a utility function to check whether an object is cyclic or not. I faced this question, in one of my previous interviews.

Firstly lets understand what "Cyclic Object" means.
A cyclic object is like any other object, but it has some property that references to any of its predecessors.
Suppose the object flow goes like this:

a -> b -> c -> d -> e
Enter fullscreen mode Exit fullscreen mode

So a,b,c,d are predecessors to "e". If e is assigned any of these to itself, the object will become a cyclic object.

My Solution

  • First initialize a variable with empty array. Lets name it "refArr". It will store references for all encountered objects. Also we will keep a flag named "isCyclicFlag" that will store true if object is cyclic and false otherwise. I have taken both these variables as global, if you want you can pass them through, as parameters to the function.

  • We will then go recursively through the object and find whether the property is of type object.

  • If so, check whether the current property's value is present in the "refArr".

    1. If yes, that would mean it is referencing to any of its predecessors thus making the object cyclic. We will also keep a variable named "cyclicDetected" assigned to false initially and keep sending this as parameter to the recursion function. Actually we will use this as to flag to move out of the recursive cycle. In this case we will make the value true and pass it forward.
    2. Else, store the reference to "refArr" and keep drilling down.

Code for reference

var refArr = [];
var isCyclicFlag = false;
function isCyclic (obj, cyclicDetected) {
    if(cyclicDetected) return cyclicDetected;
    Object.keys(obj).forEach(x => {
        if(typeof obj[x]==='object') {
            console.log(refArr, obj[x])
            for(let i=0;i<refArr.length;i++) {
                if(obj[x]===refArr[i]) {
                    cyclicDetected=true;
                    isCyclicFlag = cyclicDetected;
                }
            }
            refArr.push(obj[x]);
            return isCyclic(obj[x], cyclicDetected);
        }
    })
}
isCyclic(someObj, false);
Enter fullscreen mode Exit fullscreen mode

Now printing the value of "isCyclicFlag" will get us whether the object is Cyclic or not.

Thanks for reading!

Top comments (0)