Creates a shallow copy of the given object/value.
const original = { a: 1, b: { c: 3 } };const cloned = clone(original); // => { a: 1, b: { c: 3 } }original !== cloned; // => trueoriginal.b === cloned.b; // => true
npx atmx add helper clone
Copy and paste the following method into @/utils/helpers/undefined.ts:
@/utils/helpers/undefined.ts
import { isPrimitive } from "@/helpers/is-primitive.ts"; /*** Creates a shallow copy of the given object/value.** @example* const original = { a: 1, b: { c: 3 } }* const cloned = clone(original) // => { a: 1, b: { c: 3 } }* original !== cloned // => true* original.b === cloned.b // => true*/export function clone<T>(obj: T): T {// Primitive values do not need cloning.if (isPrimitive(obj)) {return obj;} // Binding a function to an empty object creates a copy function.if (typeof obj === "function") {return obj.bind({});} const proto = Object.getPrototypeOf(obj);const newObj =typeof proto?.constructor === "function" ? new proto.constructor() : Object.create(proto); for (const key of Object.getOwnPropertyNames(obj)) {newObj[key] = obj[key as keyof T];} return newObj;}