Skip to content

Instantly share code, notes, and snippets.

@js2me
Last active December 17, 2021 09:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save js2me/e8d69d6f30497eb091e71383deeb9257 to your computer and use it in GitHub Desktop.
Save js2me/e8d69d6f30497eb091e71383deeb9257 to your computer and use it in GitHub Desktop.
deep copy js
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