Last active
February 11, 2025 18:32
-
-
Save MarekZeman91/cfacde15bdc0e6aa615f06cbb5b5099c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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