Last active
December 17, 2021 09:40
-
-
Save js2me/e8d69d6f30497eb091e71383deeb9257 to your computer and use it in GitHub Desktop.
deep copy js
This file contains hidden or 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
export const clone = <O extends unknown | unknown[]>(value: O, history?: Set<unknown>): O => { | |
if (value == null || typeof value !== "object") return value; | |
const stack = history || new WeakSet(); | |
if (stack.has(value)) { | |
return value; | |
} | |
stack.add(value); | |
if (Array.isArray(value)) return value.map((element) => clone(element, stack)) as O; | |
const newObject: Record<string | number | symbol, unknown> = {}; | |
// eslint-disable-next-line guard-for-in | |
for (const key in value) { | |
newObject[key] = clone(value[key], stack); | |
} | |
return newObject as O; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment