forked from simov/deep-copy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (73 loc) · 1.71 KB
/
index.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
;(function (name, root, factory) {
if (typeof exports === 'object') {
module.exports = factory()
}
/* istanbul ignore next */
else if (typeof define === 'function' && define.amd) {
define(factory)
}
else {
root[name] = factory()
}
}('dcopy', this, function () {
/**
* Deep copy objects and arrays
*
* @param {Object/Array} target
* @return {Object/Array} copy
* @api public
*/
return function (target) {
if (/number|string|boolean/.test(typeof target)) {
return target
}
if (target instanceof Date) {
return new Date(target.getTime())
}
var copy = (target instanceof Array) ? [] : {}
walk(target, copy)
return copy
function walk (target, copy) {
for (var key in target) {
var obj = target[key]
if (obj instanceof Date) {
var value = new Date(obj.getTime())
add(copy, key, value)
}
else if (obj instanceof Function) {
var value = obj
add(copy, key, value)
}
else if (obj instanceof Array) {
var value = []
var last = add(copy, key, value)
walk(obj, last)
}
else if (obj instanceof Object) {
var value = {}
var last = add(copy, key, value)
walk(obj, last)
}
else {
var value = obj
add(copy, key, value)
}
}
}
}
/**
* Adds a value to the copy object based on its type
*
* @api private
*/
function add (copy, key, value) {
if (copy instanceof Array) {
copy.push(value)
return copy[copy.length - 1]
}
else if (copy instanceof Object) {
copy[key] = value
return copy[key]
}
}
}))