Created
July 29, 2020 11:58
-
-
Save Troland/e8095410fabd30393e795f654bb7d8bd to your computer and use it in GitHub Desktop.
deepClone include prop of date, regexp etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepClone(obj) { | |
function getType(obj) { | |
return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); | |
} | |
const type = getType(obj) | |
if (!obj || typeof obj !== 'object') { | |
return obj | |
} | |
// Dom Node | |
if (obj.nodeType && 'cloneNode' in obj) { | |
return obj.cloneNode(true); | |
} | |
// Date | |
if (type === 'date') { | |
const timestamp = obj.getTime() | |
return new Date(timestamp) | |
} | |
// RegExp | |
if (type === 'regexp') { | |
const flags = []; | |
if (obj.multiline) { | |
flags.push('m') | |
} | |
if (obj.ignoreCase ) { | |
flags.push('i') | |
} | |
if (obj.global) { | |
flags.push('g') | |
} | |
return new RegExp(obj.source, flags.join('')) | |
} | |
let result = type === 'array' ? [] : | |
obj.constructor ? new obj.constructor() : {} | |
for (const prop in obj) { | |
if (obj.hasOwnProperty(prop)) { | |
result[prop] = deepClone(obj[prop]) | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment