@bemedev/types
Version:
Type definitions for Bemedev projects
1 lines • 3.2 kB
Source Map (JSON)
{"version":3,"file":"deepclone.cjs","sources":["../../src/functions/deepclone.ts"],"sourcesContent":["import type { PrimitiveObject } from '../types/types';\n\nexport type FormatKey<T = any> = (key: Extract<keyof T, string>) => string;\n\n/**\n * Creates a deep clone of an object or array, preserving its structure and values.\n *\n *\n * @param value of type {@linkcode PrimitiveObject} The value to deep clone, which can be an object, array, or primitive.\n * @param formatKey A function to format the keys of the cloned object. If not provided, keys will remain unchanged.\n * @param refs A map to keep track of already cloned objects to handle circular references.\n * This is used to prevent infinite loops when cloning objects that reference each other.\n * @returns A deep clone of the input value, preserving the structure and values of the original object or array.\n *\n * Inspired by the `deep-clone` npm {@link https://www.npmjs.com/package/deep-clone|library},\n * @see the {@link https://github.com/thebearingedge/deep-clone/blob/main/src/deep-clone.ts|implementation} for more details.\n */\nexport default function deepClone<I extends PrimitiveObject>(\n value: I,\n refs = new Map<I, I>(),\n): I {\n const ref = refs.get(value);\n if (typeof ref !== 'undefined') return ref;\n\n if (Array.isArray(value)) {\n const clone: any = [];\n refs.set(value, clone);\n\n for (let i = 0; i < value.length; i++) {\n clone[i] = deepClone(value[i], refs as any);\n }\n\n return clone as I;\n }\n\n if (!(value instanceof Object)) return value as unknown as I;\n\n const clone: Record<string, PrimitiveObject> = {};\n refs.set(value, clone as I);\n const keys = Object.keys(value);\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n clone[key] = deepClone((value as any)[keys[i]], refs);\n }\n\n if (Object.isFrozen(value)) {\n Object.freeze(clone);\n }\n\n if (Object.isSealed(value)) {\n Object.seal(clone);\n }\n\n return clone as I;\n}\n"],"names":[],"mappings":";;AAIA;;;;;;;;;;;;AAYG;AACW,SAAU,SAAS,CAC/B,KAAQ,EACR,IAAA,GAAO,IAAI,GAAG,EAAQ,EAAA;IAEtB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;IAC3B,IAAI,OAA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