Skip to content

Instantly share code, notes, and snippets.

@Troland
Created July 29, 2020 11:58
Show Gist options
  • Save Troland/e8095410fabd30393e795f654bb7d8bd to your computer and use it in GitHub Desktop.
Save Troland/e8095410fabd30393e795f654bb7d8bd to your computer and use it in GitHub Desktop.
deepClone include prop of date, regexp etc.
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