File size: 1,057 Bytes
9ada4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Logger } from '@open-draft/logger'

const logger = new Logger('cloneObject')

function isPlainObject(obj?: Record<string, any>): boolean {
  logger.info('is plain object?', obj)

  if (obj == null || !obj.constructor?.name) {
    logger.info('given object is undefined, not a plain object...')
    return false
  }

  logger.info('checking the object constructor:', obj.constructor.name)
  return obj.constructor.name === 'Object'
}

export function cloneObject<ObjectType extends Record<string, any>>(
  obj: ObjectType
): ObjectType {
  logger.info('cloning object:', obj)

  const enumerableProperties = Object.entries(obj).reduce<Record<string, any>>(
    (acc, [key, value]) => {
      logger.info('analyzing key-value pair:', key, value)

      // Recursively clone only plain objects, omitting class instances.
      acc[key] = isPlainObject(value) ? cloneObject(value) : value
      return acc
    },
    {}
  )

  return isPlainObject(obj)
    ? enumerableProperties
    : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)
}