copy.js
 1  'use strict';
 2  
 3  var isPlainObject = require('./is-plain-object')
 4    , forEach       = require('./for-each')
 5    , extend        = require('./extend')
 6    , value         = require('./valid-value')
 7  
 8    , recursive;
 9  
10  recursive = function (to, from, cloned) {
11  	forEach(from, function (value, key) {
12  		var index;
13  		if (isPlainObject(value)) {
14  			if ((index = cloned[0].indexOf(value)) === -1) {
15  				cloned[0].push(value);
16  				cloned[1].push(to[key] = extend({}, value));
17  				recursive(to[key], value, cloned);
18  			} else {
19  				to[key] = cloned[1][index];
20  			}
21  		}
22  	}, from);
23  };
24  
25  module.exports = function (obj, deep) {
26  	var copy;
27  	if ((copy = Object(value(obj))) === obj) {
28  		copy = extend({}, obj);
29  		if (deep) {
30  			recursive(copy, obj, [[obj], [copy]]);
31  		}
32  	}
33  	return copy;
34  };