JSFiddle - React, Tailwind, and code Playground
JavaScript
function getType(obj) {
const str = Object.prototype.toString.call(obj);
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
};
if (obj instanceof Element) {
return 'element';
}
return map[str];
}
function deepCopy(ori) {
const type = getType(ori);
let copy;
switch (type) {
case 'array':
return copyArray(ori, type, copy);
case 'object':
return copyObject(ori, type, copy);
case 'function':
return copyFunction(ori, type, copy);
default:
return ori;
}
}
function copyArray(ori, type, copy = []) {
for (const [index, value] of ori.entries()) {
copy[index] = deepCopy(value);
}
return copy;
}
function copyObject(ori, type, copy = {}) {
for (const [key, value] of Object.entries(ori)) {
copy[key] = deepCopy(value);
}
return copy;
}
function copyFunction(ori, type, copy = () => {}) {
const fun = eval(ori.toString());
fun.prototype = ori.prototype
return fun
}
const originObject = {
a: 1,
b: 2,
c: {
d: 3
},
e: NaN
}
const _clone = deepCopy(originObject);
originObject.c.d = 35;
console.log('orign>>', originObject)
console.log(_clone)
const originArray = [1, 2, 3, 4, 5, {c: 6}, NaN]
const _cloneArray = deepCopy(originArray);
originArray[5].c = 35;
console.log('orign>>', originArray)
console.log(_cloneArray)
const arrOfFunction = [() => 2, {
test: () => 3,
}, Symbol('4')];
console.log('example 3>JSON>', JSON.parse(JSON.stringify(arrOfFunction)))
const _cloneArray_ = deepCopy(arrOfFunction);
let _function = (a) => 2
console.log('example deep clone function>>>', _function)
_function1 = _function;
const clone_function = deepCopy(_function);
_function = (a) =>...