// Implement polyfill for deep cloning OBject
// function deepClone(args) {
// hobbies: ['reading', 'biking'],
// birthDate: new Date(1994, 5, 24),
// // Follow up: Adding a circular reference
// original.circularRef = original;
// const cloned = deepClone(original);
// // Test the deep clone behavior
// // Check if circular reference is handled correctly
// console.log(cloned.circularRef === cloned); // true
// console.log(cloned.circularRef !== original.circularRef); // true
// console.log(cloned.address !== original.address); // true
// console.log(cloned.hobbies !== original.hobbies); // true
// console.log(cloned.birthDate !== original.birthDate); // true
// console.log(cloned.regexTest !== original.regexTest); // true
// console.log(cloned.address.city === original.address.city); // true
// Make sure you cover bases cases like object, Array, string , number, null initally then discuss on Regex, Dateand circular depedency
function deepClone(obj, seen = new WeakMap()) {
if (obj === null || typeof obj !== "object") {
// Handle circular references
// Create a new object or array based on the type
const clone = Array.isArray(obj) ? [] : {};
// Store the clone to handle circular references
// Iterate through all keys of the object or array
if (obj.hasOwnProperty(key)) {
if (value instanceof Date) {
clone[key] = new Date(value);
} else if (value instanceof RegExp) {
clone[key] = new RegExp(value.source, value.flags);
} else if (typeof value === "object") {
clone[key] = deepClone(value, seen);
// Direct copy for primitive values