Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Last active February 11, 2025 18:32
Show Gist options
  • Save MarekZeman91/cfacde15bdc0e6aa615f06cbb5b5099c to your computer and use it in GitHub Desktop.
Save MarekZeman91/cfacde15bdc0e6aa615f06cbb5b5099c to your computer and use it in GitHub Desktop.
/**
* Clone value deeply, ignore custom classes, symbols and functions
* @param value
* @return cloneOfValue
*/
export function deepClone<T>(value: T): T {
if (typeof value !== 'object' || !value) {
return value;
}
switch (value.constructor) {
case Array:
return (value as Array<T>).map(deepClone) as T;
case Object: {
const clone = {} as T;
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i++) {
const key = keys[i] as keyof T;
clone[key] = deepClone(value[key]);
}
return clone;
}
default:
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment