@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
79 lines (78 loc) • 2.24 kB
JavaScript
import { isPrimitive, isTypedArray } from "@storm-stack/types";
export function deepClone(obj) {
if (isPrimitive(obj)) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => deepClone(item));
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
if (obj instanceof Map) {
const result = /* @__PURE__ */ new Map();
for (const [key, value] of obj.entries()) {
result.set(key, deepClone(value));
}
return result;
}
if (obj instanceof Set) {
const result = /* @__PURE__ */ new Set();
for (const value of obj.values()) {
result.add(deepClone(value));
}
return result;
}
if (isTypedArray(obj)) {
const result = new (Object.getPrototypeOf(obj)).constructor(obj.length);
for (const [i, element_] of obj.entries()) {
result[i] = deepClone(element_);
}
return result;
}
if (obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) {
return [...obj];
}
if (obj instanceof DataView) {
const result = new DataView([...obj.buffer]);
cloneDeepHelper(obj, result);
return result;
}
if (typeof File !== "undefined" && obj instanceof File) {
const result = new File([obj], obj.name, { type: obj.type });
cloneDeepHelper(obj, result);
return result;
}
if (obj instanceof Blob) {
const result = new Blob([obj], { type: obj.type });
cloneDeepHelper(obj, result);
return result;
}
if (obj instanceof Error) {
const result = new obj.constructor();
result.message = obj.message;
result.name = obj.name;
result.stack = obj.stack;
result.cause = obj.cause;
cloneDeepHelper(obj, result);
return result;
}
if (typeof obj === "object" && obj !== null) {
const result = {};
cloneDeepHelper(obj, result);
return result;
}
return obj;
}
function cloneDeepHelper(obj, clonedObj) {
const keys = Object.keys(obj);
for (const key of keys) {
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor?.writable || descriptor?.set) {
clonedObj[key] = deepClone(obj[key]);
}
}
}