Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript Clone Object (Deep Copy)


May 09, 2021 CoffeeScript


Table of contents


Clone object (deep copy)

Problem

You want to copy an object that contains all its child objects.

Solution

clone = (obj) ->
  if not obj? or typeof obj isnt 'object'
    return obj

  if obj instanceof Date
    return new Date(obj.getTime()) 

  if obj instanceof RegExp
    flags = ''
    flags += 'g' if obj.global?
    flags += 'i' if obj.ignoreCase?
    flags += 'm' if obj.multiline?
    flags += 'y' if obj.sticky?
    return new RegExp(obj.source, flags) 

  newInstance = new obj.constructor()

  for key of obj
    newInstance[key] = clone obj[key]

  return newInstance

x =
  foo: 'bar'
  bar: 'foo'

y = clone(x)

y.foo = 'test'

console.log x.foo isnt y.foo, x.foo, y.foo
# => true, bar, test

Discuss

The difference between copying an object by assigning a value and copying an object through a clone function is how to handle references. Assignments only copy references to objects, while clone functions:

  • Create a brand new object
  • This new object copies all the properties of the original object.
  • And for all child objects of the original object, the clone function is called recursively, copying all the properties of each child object.

Here's an example of copying an object by assigning a value:

x =
  foo: 'bar'
  bar: 'foo'

y = x

y.foo = 'test'

console.log x.foo isnt y.foo, x.foo, y.foo
# => false, test, test

Obviously, after copying, the modification y also modifies x.