back to series

Implement a removeCycle function

In JavaScript, a cycle in an object occurs when there are circular references within the object’s structure. Circular references mean that an object references itself directly or indirectly through a chain of references.

1. Basic implementaion

Implement a removeCycle function which can take an object with circular references and delete them. It can mutate the original object.

./src/removeCycle.js
function removeCycle(inputObj) {
const visited = new WeakSet([inputObj]);
for (const key in inputObj) {
// only for non inhertied keys
if (Object.hasOwn(inputObj, key)) {
const value = inputObj[key];
if (typeof value === 'object' && value != null) {
if (visited.has(value)) {
delete inputObj[key];
}
visited.add(value);
}
}
}
}
// Usage
const obj = {
a: 1,
b: 2,
d: null
};
// create a cyclic reference
obj.c = obj;
removeCycle(obj);
/**
* Yields:
* {
"a": 1,
"b": 2,
"d": null
}
*/
console.log(obj);

Further Reading

I strongly encourage you to explore and tackle additional questions in my Recursion Questions for Frontend Interviews blog series.

By doing so, you can enhance your understanding and proficiency with recursion, preparing you to excel in your upcoming frontend interviews.

Wishing you best. Happy Interviewing 🫡.