A deep copy implementation that takes care of correct prototype chain and cycles, references - Node.js Object

Node.js examples for Object:Clone

Description

A deep copy implementation that takes care of correct prototype chain and cycles, references

Demo Code

 
/**//from  w  w w .  j a  va 2  s  . c  o m
 * a deep copy implementation that takes care of correct prototype chain
 * and cycles, references
 */
function copy(o, skipProps) {
  // used for cycle and reference detection:
  var originals = [];
  var copies = [];
  skipProps = skipProps || [];
  function deepCopy(o) {
    if (!o)
      return o; // null, undefined or falsy primitive
    if (~['object'/*, 'function'*/].indexOf(typeof o)) {
      var originalPos = originals.indexOf(o);
      if (originalPos !== -1) // we already know the object
        return copies[originalPos];

      // else: create a copy:
      var proto = Object.getPrototypeOf(o);
      // FIXME: copying functions?!?
      var copy = Object.create(proto);
      // save the copy in the cache before going over the props, in case there
      // is a cycle
      originals.push(o);
      copies.push(copy);
      
      var props = Object.getOwnPropertyNames(o);
      props.forEach(function (prop) {
        var propdesc = Object.getOwnPropertyDescriptor(o, prop);
        var newDescriptor;
        if (propdesc.get || propdesc.set) {
          // FIXME: just copy accessor properties for now before we can copy functions
          newDescriptor = propdesc;
        } else {
          // deep copy data properties
          newDescriptor = {
            writable: propdesc.writable,
            configurable: propdesc.configurable,
            enumerable: propdesc.enumerable,
            value: ~skipProps.indexOf(prop) ? propdesc.value : deepCopy(propdesc.value),
          };
        }
        Object.defineProperty(copy, prop, newDescriptor);
      });
      return copy;
    }
    return o;
  }
  return deepCopy(o);
}

Related Tutorials