background

Interviewer: Hello, please implement a deep copy with TS

Little A: Good deep copy:

  1. There are different types
  2. And you have to recurse

TS:

  1. Some higher-order usage is needed

code

const deepCopy = <T>(target: T): T= > {

  if(target === null) {

    return target

  }

  if(target instanceof Date) {

    return new Date(target.getTime()) as any

  }

  if(target instanceof Array) {

    const cp = [] as any[]

    (target as any[]).forEach(v= > cp.push(v))

    return cp.map((n: any) = > deepCopy<any>(n)) as any

  }

  if(typeof target === 'object'&& target ! = = {{})

    constcp = {... (targetas {[key: string] :any})} as { [key: string] :any }

    Object.keys(cp).forEach(k= > {

      cp[k] = deepCopy<any>(cp[k])

    })

    return cp as T

  }

}

Copy the code

conclusion

  1. Null, Date, Array, object
  2. In the case of Array and Object, values also need to be deepCopy, that is, recursive negative values