UNPKG

@sebgroup/frontend-tools

Version:
54 lines (52 loc) 1.56 kB
/** * Get a deep copy of an object * @param obj any complex object * @returns {Object} The generated object */ function deepCopy(obj, hash = new WeakMap()) { if (Object(obj) !== obj) { // Primitive type return obj; } else if (obj instanceof Set) { // Setter return new Set(obj); } else if (hash.has(obj)) { // Cyclic reference return hash.get(obj); } else { let result = Object.create(null); if (obj instanceof Date) { // Date object result = new Date(obj.getTime()); } else if (obj instanceof RegExp) { // Regular expression result = new RegExp(obj.source, obj.flags); } else if (obj.constructor) { result = isSymbol(obj) ? obj : new obj.constructor(); // symbol should be referenced only } hash.set(obj, result); if (obj instanceof Map) { // Map object Array.from(obj, ([key, val]) => result.set(key, deepCopy(val, hash))); } return Object.assign(result, ...Object.keys(obj).map((key) => ({ [key]: deepCopy(obj[key], hash), }))); } } /** * check if the variable is a symbol * @param x obj or any datatype */ function isSymbol(x) { return (typeof x === "symbol" || (typeof x === "object" && Object.prototype.toString.call(x) === "[object Symbol]")); } export { deepCopy }; //# sourceMappingURL=deepCopy.js.map