Skip to content

Instantly share code, notes, and snippets.

@magne4000
Created June 18, 2024 12:52
Show Gist options
  • Save magne4000/81d5d03ada6d925cbe8214dbda269a9a to your computer and use it in GitHub Desktop.
Save magne4000/81d5d03ada6d925cbe8214dbda269a9a to your computer and use it in GitHub Desktop.
// WIP
function tryClone<T>(obj: T): T {
try {
return structuredClone(obj);
} catch (err) {
if (obj == null || typeof obj === "function") {
return obj;
}
if (typeof obj === "object") {
if (Array.isArray(obj)) {
const cloned = [] as typeof obj;
for (const key in obj) {
cloned[key] = tryClone(obj[key]);
}
return cloned;
}
const keys = Object.keys(obj) as (keyof typeof obj)[];
const cloned = {} as typeof obj;
for (const key of keys) {
cloned[key] = tryClone(obj[key]);
}
return cloned;
}
console.log(obj);
throw err;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment