MCPcopy Index your code
hub / github.com/TanStack/db / deepClone

Function deepClone

packages/db/src/proxy.ts:514–613  ·  view source on GitHub ↗

* Deep clones an object while preserving special types like Date and RegExp

(
  obj: T,
  visited = new WeakMap<object, unknown>(),
)

Source from the content-addressed store, hash-verified

512 */
513
514function deepClone<T extends unknown>(
515 obj: T,
516 visited = new WeakMap<object, unknown>(),
517): T {
518 // Handle null and undefined
519 if (obj === null || obj === undefined) {
520 return obj
521 }
522
523 // Handle primitive types
524 if (typeof obj !== `object`) {
525 return obj
526 }
527
528 // If we've already cloned this object, return the cached clone
529 if (visited.has(obj as object)) {
530 return visited.get(obj as object) as T
531 }
532
533 if (obj instanceof Date) {
534 return new Date(obj.getTime()) as unknown as T
535 }
536
537 if (obj instanceof RegExp) {
538 return new RegExp(obj.source, obj.flags) as unknown as T
539 }
540
541 if (Array.isArray(obj)) {
542 const arrayClone = [] as Array<unknown>
543 visited.set(obj as object, arrayClone)
544 obj.forEach((item, index) => {
545 arrayClone[index] = deepClone(item, visited)
546 })
547 return arrayClone as unknown as T
548 }
549
550 // Handle TypedArrays
551 if (ArrayBuffer.isView(obj) && !(obj instanceof DataView)) {
552 // Get the constructor to create a new instance of the same type
553 const TypedArrayConstructor = Object.getPrototypeOf(obj).constructor
554 const clone = new TypedArrayConstructor(
555 (obj as unknown as TypedArray).length,
556 ) as unknown as TypedArray
557 visited.set(obj as object, clone)
558
559 // Copy the values
560 for (let i = 0; i < (obj as unknown as TypedArray).length; i++) {
561 clone[i] = (obj as unknown as TypedArray)[i]!
562 }
563
564 return clone as unknown as T
565 }
566
567 if (obj instanceof Map) {
568 const clone = new Map() as Map<unknown, unknown>
569 visited.set(obj as object, clone)
570 obj.forEach((value, key) => {
571 clone.set(key, deepClone(value, visited))

Callers 3

createChangeProxyFunction · 0.85
setFunction · 0.85
definePropertyFunction · 0.85

Calls 6

isTemporalFunction · 0.90
hasMethod · 0.45
getMethod · 0.45
setMethod · 0.45
forEachMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…