-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeepclonefunc.js
92 lines (90 loc) · 2.83 KB
/
deepclonefunc.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
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
# Deep Cloning Objects and Arrays with Func
A Javascript function that deep clones objects and arrays and calls a function
on an element that is not an array, set, or map.
─────────────────────────────────────────────────────────────────────────────
Author: @RockStarwind
Date: 2019-19-10
Version: 1.0.0 (based on deepclone.js 1.0.2)
Repo: https://github.com/RockStarwind/js-functions
License: MIT
─────────────────────────────────────────────────────────────────────────────
Polyfill for Object.assign:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
*/
function deepCloneFunc(obj, func) {
if (typeofObject(func) !== "[object Function]") {
func = function(obj) { return obj }
}
function typeofObject(obj) {
return Object.prototype.toString.call(obj);
}
function isArray(obj) {
return typeofObject(obj) === "[object Array]";
}
function isHash(obj) {
return typeofObject(obj) === "[object Object]";
}
function isMap(obj) {
return typeofObject(obj) === "[object Map]"
}
function isSet(obj) {
return typeofObject(obj) === "[object Set]"
}
function arrayShallowClone(obj) {
return obj.slice(0);
}
function hashShallowClone(obj) {
return Object.assign({}, obj);
}
var newObj;
var set = false;
var map = false;
// Is this a set or a map?
if (isSet(obj) || isMap(obj)) {
newObj = [];
// Convert the set into an array
if (isSet(obj)) {
obj.forEach(function (value) { return newObj.push(value) });
set = true;
}
if (isMap(obj)) {
obj.forEach(function (value, key) { return newObj.push([key, value]) });
map = true;
}
obj = arrayShallowClone(newObj);
}
// Is this an array or a hash table?
if (isArray(obj) || isHash(obj)) {
// Is this an array?
if (isArray(obj)) {
// Shallow clone the array
newObj = arrayShallowClone(obj);
// Loop through newObj's elements
for (var i = 0; i < newObj.length; i++) {
newObj[i] = deepCloneFunc(newObj[i], func);
}
}
// Is this a hash?
else {
// Shallow clone the hash object
newObj = hashShallowClone(obj);
// Loop through newObj's properties
for (var prop in newObj) {
newObj[prop] = deepCloneFunc(newObj[prop], func);
}
}
// Did this object begin as either a set or a map?
if (set || map) {
// Convert it back into a set
if (set) { newObj = new Set(newObj.slice(0)); }
// Convert it back into a map
if (map) { newObj = new Map(newObj.slice(0)); }
}
return newObj;
}
// Is this something other than an array or hash?
else {
return func(obj);
}
}